import std.stdio;
import std.conv, std.array, std.algorithm, std.string;
import std.math, std.random, std.range, std.datetime;
import std.bigint;

int[] calclife(int[] as){
	int n = as.length;
	
	debug writeln;
	debug as.writeln;
	debug writeln("---");
	
	int[] life;
	life.length = n + 1;
	
	int[] stack;
	int[] stack2;
	foreach(i; 0 .. n){
		int a = as[i];
		if(stack.length == 0){
			stack ~= a;
			stack2 ~= 1;
			continue;	
			}
		if(stack[$ - 1] < a){
			stack ~= a;
			stack2 ~= 1;
			}
		else{
			int len = 1;
			while(stack.length){
				if(stack[$ - 1] < a) break;
				life[stack[$ - 1]] = stack2[$ - 1];
				if(stack.length > 1) stack2[$ - 2] += stack2[$ - 1];
				stack.length -= 1;
				stack2.length -= 1;
				}
			stack ~= a;
			stack2 ~= 1;
			}
		debug stack.writeln;
		debug stack2.writeln;
		debug life.writeln;
		}
	{
		while(stack.length){
			life[stack[$ - 1]] = stack2[$ - 1];
			if(stack.length > 1) stack2[$ - 2] += stack2[$ - 1];
			stack.length -= 1;
			stack2.length -= 1;
			}
		debug stack.writeln;
		debug stack2.writeln;
		debug life.writeln;
		}
	
	return life;
	}


void main(){
	int n = readln.chomp.to!int;
	int[] as = readln.chomp.split.map!(to!int).array;
	
	int[] life = calclife(as);
	as.reverse();
	int[] life2 = calclife(as);
	
	debug writeln;
	debug life.writeln;
	debug life2.writeln;
	
	long ans;
	foreach(i; 0 .. life.length) ans += life[i] * life2[i] * i;
	
	ans.writeln;
	}