import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    void solve() {
        int n=ni(); long I=nl()*8;
        int a[]= new int[n+1];
        for(int i=1;i<=n;i++) a[i]=ni();
        Arrays.sort(a,1,n+1);
        int cc[]=new int[n+1];

        int pref[]=new int[n+1];

        a[0]=-1;

        for(int i=1;i<=n;i++){
            pref[i]=pref[i-1];
            cc[i]=1;
            if(a[i]!=a[i-1]){
                pref[i]++;

            }else  cc[i]+=cc[i-1];

        }

        int cc2[]=new int[n+2];
        cc2[n]=1;
        for(int i=n-1;i>=1;i--){
            cc2[i]=1;
            if(a[i]==a[i+1]) cc2[i]+=cc2[i+1];
        }
        int ans=Integer.MAX_VALUE;

        int val[]=new int[n+1];
        for(int i=1;i<=n;i++) val[i]=get(i);
        int l,r,idx,mid;
        for(int i=1;i<=n;i++){
             l=i; r=n; idx=-1;
            while(l<=r){
                mid=(l+r)>>1;
                if(n*1L*val[pref[mid]-pref[i-cc[i]]]<=I){
                    idx=mid;
                    l=mid+1;
                }else r=mid-1;
            }
           ans=Math.min(ans,i-cc[i]+(n-(idx+cc2[idx]-1)));
           i+=cc2[i]-1;

        }
        pw.println(ans);
    }
    int get(int n){
        int cc=0;
        n--;
        while(n>0){
            n/=2;
            cc++;
        }
        return cc;
    }

    long M = (long) 1e9 + 7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    void solve() {
        int n=ni(); long I=nl()*8;
        ArrayList<Integer> arr=new ArrayList<>();

        int a[]= new int[n+1];
        for(int i=1;i<=n;i++) arr.add(ni());
        Collections.sort(arr);
        for(int i=1;i<=n;i++) a[i]=arr.get(i-1);
        int cc[]=new int[n+1];

        int pref[]=new int[n+1];

        a[0]=-1;

        for(int i=1;i<=n;i++){
            pref[i]=pref[i-1];
            cc[i]=1;
            if(a[i]!=a[i-1]){
                pref[i]++;

            }else  cc[i]+=cc[i-1];

        }

        int cc2[]=new int[n+2];
        cc2[n]=1;
        for(int i=n-1;i>=1;i--){
            cc2[i]=1;
            if(a[i]==a[i+1]) cc2[i]+=cc2[i+1];
        }
        int ans=Integer.MAX_VALUE;

        int val[]=new int[n+1];
        for(int i=1;i<=n;i++) val[i]=get(i);
        int l,r,idx,mid;
        for(int i=1;i<=n;i++){
             l=i; r=n; idx=-1;
            while(l<=r){
                mid=(l+r)>>1;
                if(n*1L*val[pref[mid]-pref[i-cc[i]]]<=I){
                    idx=mid;
                    l=mid+1;
                }else r=mid-1;
            }
           ans=Math.min(ans,i-cc[i]+(n-(idx+cc2[idx]-1)));
           i+=cc2[i]-1;

        }
        pw.println(ans);
    }
    int get(int n){
        int cc=0;
        n--;
        while(n>0){
            n/=2;
            cc++;
        }
        return cc;
    }

    long M = (long) 1e9 + 7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    void solve() {
        int n=ni(); long I=nl()*8;
        int a[]= new int[n+1];
        for(int i=1;i<=n;i++) a[i]=ni();
        Arrays.sort(a,1,n+1);
        int cc[]=new int[n+1];

        int pref[]=new int[n+1];

        a[0]=-1;

        for(int i=1;i<=n;i++){
            pref[i]=pref[i-1];
            cc[i]=1;
            if(a[i]!=a[i-1]){
                pref[i]++;

            }else  cc[i]+=cc[i-1];

        }
        int suf[]=new int[n+2];
        suf[n]=1;
        for(int i=n-1;i>=1;i--){
            suf[i]=suf[i+1];
            if(a[i]!=a[i+1]) suf[i]++;
        }
        int cc2[]=new int[n+2];
        cc2[n]=1;
        for(int i=n-1;i>=1;i--){
            cc2[i]=1;
            if(a[i]==a[i+1]) cc2[i]+=cc2[i+1];
        }
        int ans=Integer.MAX_VALUE;

        int val[]=new int[n+1];
        for(int i=1;i<=n;i++) val[i]=get(i);

        for(int i=1;i<=n;i++){
            int l=i,r=n,idx=-1;
            while(l<=r){
                int mid=(l+r)>>1;
                if(n*1L*val[pref[mid]-pref[i-cc[i]]]<=I){
                    idx=mid;
                    l=mid+1;
                }else r=mid-1;
            }
           ans=Math.min(ans,i-cc[i]+(n-(idx+cc2[idx]-1)));

        }
        pw.println(ans);
    }
    int get(int n){
        int cc=0;
        n--;
        while(n>0){
            n/=2;
            cc++;
        }
        return cc;
    }

    long M = (long) 1e9 + 7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var input = rdArN();
    var n = input[0];
    var I = input[1];
    var A = rdArN();

    var M = {};
    for (var i = 0; i < A.length; ++i) {
        var val = A[i];
        M[val] = ++M[val] || 1;
    }

    var K = Object.keys(M);
    var uniqueK = K.length;

    var fullBits = I*8;
    var bitsForElem = Math.floor(fullBits/n);
    var maxUniqueK = Math.pow(2, bitsForElem);

    if (maxUniqueK >= uniqueK) {
        wr(0);
    } else {
        var needToCut = uniqueK - maxUniqueK;
        //prOb(M);
        var Klen = K.length;
        var superA = [];
        for (var i = 0; i < K.length; ++i) {
            superA.push(M[K[i]]);
        }
        superA = superA.concat(superA);
        //prAr(superA);
        var sum = 0;
        for (var i = Klen - needToCut; i < Klen; ++i) {
            sum += superA[i];
        }
        //pr(sum)
        var subsum = sum;
        var cnt = 0;
        for (var l = Klen - needToCut, r = Klen; l < Klen; ++l, ++r) {
            cnt++;
            subsum -= superA[l];
            subsum += superA[r];
            if (subsum < sum) {
                sum = subsum;
            }
        }
        //pr(needToCut, cnt);
        wr(sum);
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});
defineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});
defineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});
defineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});

main();
return OUTPUT;
})();


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n;
ll l,r,ans,a[1000001];
vector<int>v[1000001],g;
set<int>st;
set<ll>::iterator it;
ll sol(){
	ll ans=0;
	set<ll>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		scanf("%I64d",&a[i]);
		v[a[i]].pb(i);
	}
	for(int i=1; i<=1000000; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	ll ans1 = sol();
	g.clear();

	for(int i=1000000; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	ll ans2 = sol();

	cout<<ans2 - ans1;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mx,l,r,a[1000001];
ll ans;
vector<int>v[1000001],g;
set<int>::iterator it,it1;
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&a[i]);
		v[a[i]].pb(i);
		if(a[i]>mx)mx=a[i];
	}
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	g.clear();
	for(int i=mx; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	set<int>st1;
	st1.insert(0);
	st1.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st1.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st1.insert(g[i]);
	}

	cout<<ans;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mx,l,r,ans,a[1000001];
vector<int>v[1000001],g;
set<int>::iterator it,it1;
int main(){
//	std::ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&a[i]);
		v[a[i]].pb(i);
		if(a[i]>mx)mx=a[i];
	}
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	g.clear();

	for(int i=mx; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	set<int>st1;
	st1.insert(0);
	st1.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st1.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st1.insert(g[i]);
	}

	cout<<ans;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k;
vector<int>v[1000001];
int g[1000001];
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<k; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x > mx)mx = x;
	}
	k=0;
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	ll ans1 = sol();
	k=0;
	for(int i=mx; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g[k] = v[i][j],k++;
	ll ans2 = sol();

	cout<<ans2 - ans1;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k;
vector<int>v[1000001];
int g[1000001];
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=k-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<=n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x > mx)mx = x;
	}
	k=0;
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	cout<<sol();

	return 0;
}
//**


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k;
vector<int>v[1000001];
int g[1000001];
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=k-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<=n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x > mx)mx = x;
	}
	k=0;
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	cout<<sol();

	////
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n;
ll l,r,ans,a[1000001];
vector<int>v[1000001],g;
set<int>st;
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<ll>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		scanf("%I64d",&a[i]);
		v[a[i]].pb(i);
	}
	for(int i=1; i<=1000000; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	ll ans1 = sol();
	g.clear();

	for(int i=1000000; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	ll ans2 = sol();

	cout<<ans2 - ans1;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k;
vector<int>v[1000001];
int g[1000001];
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=k-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<=n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x > mx)mx = x;
	}
	k=0;
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	cout<<sol();

	////

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k;
vector<int>v[1000001];
int g[1000001];
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=k-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<k; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){ // gogo
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x > mx)mx = x;
	}
	k=0;
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	cout<<sol();

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001];
vector<int>v[1000001],g;
set<int>::iterator it,it1;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it1 = st.lower_bound(g[i]);
		it = it1;
		it1--;
		ans += (ll)(g[i] - *it) * (ll)(*it1 - g[i]) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x>mx)mx=x;
	}
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	ll ans1 = sol();
	g.clear();

	for(int i=mx; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	ll ans2 = sol();

	printf("%I64d",ans2-ans1);

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
ll n,l,r,ans,a[1000001];
vector<ll>v[1000001],g;
set<ll>st;
set<ll>::iterator it;
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		scanf("%I64d",&a[i]);
		v[a[i]].pb(i);
	}
	for(int i=1; i<=1000000; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	ll ans1=0;
	set<ll>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans1 += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}
	g.clear();

	for(int i=1000000; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	ll ans2=0;
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans2 += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}

	cout<<ans2 - ans1;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,a[1000001],g[1000001],x;
vector<int>v[1000001];
pair<int,int> gg[1000001];
set<int>::iterator it;
ll ans=0;
set<int>st;
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		scanf("%d",&x);
		a[i] = x;
		gg[i] = make_pair(x,i);
	}
	sort(gg + 1,gg + n + 1);
	for(int i=1; i<=n; i++)
		g[i - 1] = gg[i].s;

	st.insert(0);
	st.insert(n+1);
	for(int i=n-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	cout<<ans;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k,g[1000001];
vector<int>v[1000001];
vector< pair<int,int> > gg;
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=n-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		gg.pb(make_pair(x,i));
	}
	k=0;
	sort(gg.begin(),gg.end());
	for(int i=0; i<gg.size(); i++){
		g[i] = gg[i].s;
	}
//	for(int i=1; i<=mx; i++)
//		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=n-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	cout<<ans;

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k;
vector<int>v[1000001];
int g[1000001];
set<int>::iterator it;
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		v[x].pb(i);
		if(x > mx)mx = x;
	}
	k=0;
	for(int i=1; i<=mx; i++)
		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
		ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=k-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<k; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	cout<<ans;

	return 0;
}
///


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
int n,mn,mx,l,r,ans,a[1000001],k,g[1000001];
vector<int>v[1000001];
vector< pair<ll,ll> > gg;
set<int>::iterator it;
ll sol(){
	ll ans=0;
	set<int>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=n-1; i>=0; i--){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<n; i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans -= (ll)(g[i] - l + 1) * (ll)(r - g[i] + 1) * (ll)a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		int x;
		scanf("%d",&x);
		a[i] = x;
		gg.pb(make_pair(x,i));
	}
	k=0;
	sort(gg.begin(),gg.end());
	for(int i=0; i<gg.size(); i++){
		g[i] = gg[i].s;
	}
//	for(int i=1; i<=mx; i++)
//		for(int j=0; j<v[i].size(); j++)g[k]=v[i][j],k++;
	cout<<sol();

	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define f first
#define s second
#define pb push_back
#define mp make_pair
using namespace std;
ll n,l,r,ans,a[1000001];
vector<ll>v[1000001],g;
set<ll>st;
set<ll>::iterator it;
ll sol(){
	ll ans=0;
	set<ll>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i=1; i<=n; i++){
		scanf("%I64d",&a[i]);
		v[a[i]].pb(i);
	}
	for(int i=1; i<=1000000; i++)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);

	ll ans1=0;
	set<ll>st;
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans1 += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}
	g.clear();

	for(int i=1000000; i>=1; i--)
		for(int j=0; j<v[i].size(); j++)g.pb(v[i][j]);
	ll ans2=0;
	st.clear();
	st.insert(0);
	st.insert(n+1);
	for(int i=0; i<g.size(); i++){
		it = st.lower_bound(g[i]);
		r = *(it) - 1;
		it--;
		l = *it + 1;
		ans2 += (g[i] - l + 1) * (r - g[i] + 1) * a[g[i]];
		st.insert(g[i]);
	}

	cout<<ans2 - ans1;

	return 0;
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma warning(disable:4996)
//#pragma comment(linker, "/STACK:512000000")

//190647WR

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <functional>
#include <iterator>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <string>

#define ISO11
#define myDEBUG

#ifdef ISO11
#include <unordered_map>
#include <unordered_set>
#endif

#ifdef myDEBUG

#define assert(x) \
	if(!x){\
		cerr<<"\n\nERROR!\tFailed: "<<x;\
		cerr<<"\nLine: "<<__LINE__;\
		cerr<<"\nFile: "<<__FILE__;\
		cerr<<"\nTime: "<<__TIME__;\
		cerr<<"\nDate: "<<__DATE__;\
	}\

#define err(x) assert(x)
#define warn(x) assert(x)

#endif

#define F first
#define S second
#define read(x) scanf("%d", &x);
#define readln(x) scanf("%d\n", &x);
#define write(x) printf("%d ", x);
#define writeln(x) printf("%d\n", x);
#define forn(i, n) for(int i = 0; i < n; ++i)
#define MEM(x, y) memset(x, y, sizeof(x));
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define runtime clock() * 1.0 / CLOCKS_PER_SEC

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
//typedef pair<int, int> pii;
#define pii pair<int, int>
const ll INF = (1ll << 63) - 1ll;
const ld INFd = 28e14;
const ll inf = (1 << 31) - 1;
const ld EPS = 1e-8;

const ld PI = acos(-1.0);
const ll mod = 7 + 1e9;

using namespace std;

//#include <chrono>
//using namespace std::chrono;
//cerr << "Nanosec:" << duration_cast<nanoseconds>(end_time - start_time).count() << endl;
//time_point<steady_clock> start_time, end_time;
//start_time = high_resolution_clock::now();
//end_time = high_resolution_clock::now();

void OUT(bool f) { if (f) cout << "YES" << endl; else cout << "NO" << endl; }
void Out(bool f) { if (f) cout << "Yes" << endl; else cout << "No" << endl; }
void out(bool f) { if (f) cout << "yes" << endl; else cout << "no" << endl; }

inline int next_rand() { return abs(rand() * rand() + rand()); }

struct __debug__ {
	__debug__(string filename, bool f = false) {
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
		if (filename == "") return;
		ios_base::sync_with_stdio(0);
		cin.tie(0);
		cout.tie(0);
		string filein = filename + ".in";
		string fileout = filename + ".out";
		freopen(filein.c_str(), "r", stdin);
		freopen(fileout.c_str(), "w", stdout);
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
	}
	~__debug__() {
#ifdef _DEBUG
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		cerr << "\n\nTIME: \t" << runtime << endl;
		system("pause");
#endif
	}
};

__debug__ DEBUG("");

//#define STRESS
void gen();
void solve();

//#define GEOM

int main() {
	srand('M' + 'A' + 'S' + 'L' + '0' + 'F');
	srand(time(0));
#ifdef STRESS
	gen();
#endif
	/// zahijoja
	/// aawnrjn6
	/// ugesetacuz
	/// fml31-p08
	/// shop-3
	/// yedetayiro
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	solve();
	//afesivuda
	//ivisuzedu
}
//bool dbg = true;
const int maxn = 1000000;
int a[maxn];

ll stress(int l, int r) {
	ll ans = 0;
	for (int i = l; i < r; ++i)
		for (int j = i + 1; j < r; ++j)
			ans += *max_element(a + i, a + j + 1) - *min_element(a + i, a + j + 1);
	return ans;
}

int maxl[maxn];
int maxr[maxn];
int minl[maxn];
int minr[maxn];
ll pmaxl[maxn];
ll pmaxr[maxn];
ll pminl[maxn];
ll pminr[maxn];
int n;

ll askminr(int l, int r) {
	return pminr[r - 1] - pminr[l - 1];
}
ll askmaxr(int l, int r) {
	return pmaxr[r - 1] - pmaxr[l - 1];
}

ll askminl(int l, int r) {
	return pminl[l] - pminl[r];
}
ll askmaxl(int l, int r) {
	return pmaxl[l] - pmaxl[r];
}

void cnt_pref(int l, int r) {
	int m = l + r >> 1;
	if (dbg) {
		MEM(pminr, 0);
		MEM(pmaxr, 0);
		MEM(pminl, 0);
		MEM(pmaxl, 0);
	}
	pminr[m] = minr[m];
	pmaxr[m] = maxr[m];
	for (int i = m + 1; i < r; ++i) {
		pminr[i] = (pminr[i - 1] + minr[i]);
		pmaxr[i] = (pmaxr[i - 1] + maxr[i]);
	}
	pminl[m - 1] = minl[m - 1];
	pmaxl[m - 1] = maxl[m - 1];
	for (int i = m - 2; i >= l; --i) {
		pminl[i] = (pminl[i + 1] + minl[i]);
		pmaxl[i] = (pmaxl[i + 1] + maxl[i]);
	}
	pmaxl[m] = 0;
	pminl[m] = 0;
}

ll merg(int l = 0, int r = n) {
	if (r - l == 1)return 0;
	int m = l + r >> 1;
	ll ans = merg(l, m) + merg(m, r);
	if (dbg) {
		MEM(minr, 0);
		MEM(maxr, 0);
		MEM(minl, 0);
		MEM(maxl, 0);
	}
	minr[m] = a[m];
	maxr[m] = a[m];
	for (int i = m + 1; i < r; ++i) {
		minr[i] = min(minr[i - 1], a[i]);
		maxr[i] = max(maxr[i - 1], a[i]);
	}
	minl[m - 1] = a[m - 1];
	maxl[m - 1] = a[m - 1];
	for (int i = m - 2; i >= l; --i) {
		minl[i] = min(minl[i + 1], a[i]);
		maxl[i] = max(maxl[i + 1], a[i]);
	}

	cnt_pref(l, r);

	int L = m;
	int R = m;

	int p = m - 1;

	for (; p >= l; --p) {
		while (L < r && minr[L] >= minl[p])++L;
		while (R < r && maxr[R] <= maxl[p])++R;
		ans += 1ll * (maxl[p] - minl[p]) * (min(L, R) - m);
		if (L == R) {
			ans += askmaxr(R, r) - askminr(L, r);
			continue;
		}
		if (L < R) {
			ans += maxl[p] * (R - L - 0ll) - askminr(L, R);
			ans += askmaxr(R, r) - askminr(R, r);
		}
		else {
			ans += askmaxr(R, L) - minl[p] * (L - R - 0ll);
			ans += askmaxr(L, r) - askminr(L, r);
		}
	}
	//cerr << l << ' ' << r << " = " << ans << " ? " << stress(l, r) << endl;
	return ans;
}

void solve() {
	cin >> n;
	for (int i = 0; i < n; ++i)cin >> a[i];
	cout << merg();
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma warning(disable:4996)
//#pragma comment(linker, "/STACK:512000000")

//190647WR

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <functional>
#include <iterator>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <string>

#define ISO11
#define myDEBUG

#ifdef ISO11
#include <unordered_map>
#include <unordered_set>
#endif

#ifdef myDEBUG

#define assert(x) \
	if(!x){\
		cerr<<"\n\nERROR!\tFailed: "<<x;\
		cerr<<"\nLine: "<<__LINE__;\
		cerr<<"\nFile: "<<__FILE__;\
		cerr<<"\nTime: "<<__TIME__;\
		cerr<<"\nDate: "<<__DATE__;\
	}\

#define err(x) assert(x)
#define warn(x) assert(x)

#endif

#define F first
#define S second
#define read(x) scanf("%d", &x);
#define readln(x) scanf("%d\n", &x);
#define write(x) printf("%d ", x);
#define writeln(x) printf("%d\n", x);
#define forn(i, n) for(int i = 0; i < n; ++i)
#define MEM(x, y) memset(x, y, sizeof(x));
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define runtime clock() * 1.0 / CLOCKS_PER_SEC

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
//typedef pair<int, int> pii;
#define pii pair<int, int>
const ll INF = (1ll << 63) - 1ll;
const ld INFd = 28e14;
const ll inf = (1 << 31) - 1;
const ld EPS = 1e-8;

const ld PI = acos(-1.0);
const ll mod = 7 + 1e9;

using namespace std;

//#include <chrono>
//using namespace std::chrono;
//cerr << "Nanosec:" << duration_cast<nanoseconds>(end_time - start_time).count() << endl;
//time_point<steady_clock> start_time, end_time;
//start_time = high_resolution_clock::now();
//end_time = high_resolution_clock::now();

void OUT(bool f) { if (f) cout << "YES" << endl; else cout << "NO" << endl; }
void Out(bool f) { if (f) cout << "Yes" << endl; else cout << "No" << endl; }
void out(bool f) { if (f) cout << "yes" << endl; else cout << "no" << endl; }

inline int next_rand() { return abs(rand() * rand() + rand()); }

struct __debug__ {
	__debug__(string filename, bool f = false) {
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
		if (filename == "") return;
		ios_base::sync_with_stdio(0);
		cin.tie(0);
		cout.tie(0);
		string filein = filename + ".in";
		string fileout = filename + ".out";
		freopen(filein.c_str(), "r", stdin);
		freopen(fileout.c_str(), "w", stdout);
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
	}
	~__debug__() {
#ifdef _DEBUG
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		cerr << "\n\nTIME: \t" << runtime << endl;
		system("pause");
#endif
	}
};

__debug__ DEBUG("");

//#define STRESS
void gen();
void solve();

//#define GEOM

int main() {
	srand('M' + 'A' + 'S' + 'L' + '0' + 'F');
	srand(time(0));
#ifdef STRESS
	gen();
#endif
	/// zahijoja
	/// aawnrjn6
	/// ugesetacuz
	/// fml31-p08
	/// shop-3
	/// yedetayiro
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	solve();
	//afesivuda
	//ivisuzedu
}

const int maxn = 100;
int a[maxn];
int maxl[maxn];
int maxr[maxn];
int minl[maxn];
int minr[maxn];
ll pmaxl[maxn];
ll pmaxr[maxn];
ll pminl[maxn];
ll pminr[maxn];
int n;

ll askminr(int l, int r) {
	return pminr[r - 1] - pminr[l - 1];
}
ll askmaxr(int l, int r) {
	return pmaxr[r - 1] - pmaxr[l - 1];
}

ll askminl(int l, int r) {
	return pminl[l] - pminl[r];
}
ll askmaxl(int l, int r) {
	return pmaxl[l] - pmaxl[r];
}

void cnt_pref(int l, int r) {
	int m = l + r >> 1;
	pminr[m] = minr[m];
	pmaxr[m] = maxr[m];
	for (int i = m + 1; i < r; ++i) {
		pminr[i] = (pminr[i - 1] + minr[i]);
		pmaxr[i] = (pmaxr[i - 1] + maxr[i]);
	}
	pminl[m - 1] = minl[m - 1];
	pmaxl[m - 1] = maxl[m - 1];
	for (int i = m - 2; i >= l; --i) {
		pminl[i] = (pminl[i + 1] + minl[i]);
		pmaxl[i] = (pmaxl[i + 1] + maxl[i]);
	}
	pmaxl[m] = 0;
	pminl[m] = 0;
}

ll merg(int l = 0, int r = n) {
	if (r - l == 1)return 0;
	int m = l + r >> 1;
	ll ans = merg(l, m) + merg(m, r);
	minr[m] = a[m];
	maxr[m] = a[m];
	for (int i = m + 1; i < r; ++i) {
		minr[i] = min(minr[i - 1], a[i]);
		maxr[i] = max(maxr[i - 1], a[i]);
	}
	minl[m - 1] = a[m - 1];
	maxl[m - 1] = a[m - 1];
	for (int i = m - 2; i >= l; --i) {
		minl[i] = min(minl[i + 1], a[i]);
		maxl[i] = max(maxl[i + 1], a[i]);
	}

	cnt_pref(l, r);

	int L = m;
	int R = m;

	int p = m - 1;

	for (; p >= l; --p) {
		while (L < r && minr[L] > minl[p])++L;
		while (R < r && maxr[R] < maxl[p])++R;
		ans += 1ll * (maxl[p] - minl[p]) * (min(L, R) - p);
		if (L == R) {
			ans += askmaxr(R, r) - askminr(L, r);
			continue;
		}
		if (L < R) {
			ans += maxl[p] * (L - p - 0ll) - askminr(L, R);
			ans += askmaxr(R, r) - askminr(R, r);
		}
		else {
			ans += askmaxr(R, L) - minl[p] * (R - p - 0ll);
			ans += askmaxr(L, r) - askminr(L, r);
		}
	}
	//cerr << l << ' ' << r << " = " << ans << endl;
	return ans;
}

void solve() {
	cin >> n;
	for (int i = 0; i < n; ++i)cin >> a[i];
	cout << merg();
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma warning(disable:4996)
//#pragma comment(linker, "/STACK:512000000")

//190647WR

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <functional>
#include <iterator>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <string>

#define ISO11
#define myDEBUG

#ifdef ISO11
#include <unordered_map>
#include <unordered_set>
#endif

#ifdef myDEBUG

#define assert(x) \
	if(!x){\
		cerr<<"\n\nERROR!\tFailed: "<<x;\
		cerr<<"\nLine: "<<__LINE__;\
		cerr<<"\nFile: "<<__FILE__;\
		cerr<<"\nTime: "<<__TIME__;\
		cerr<<"\nDate: "<<__DATE__;\
	}\

#define err(x) assert(x)
#define warn(x) assert(x)

#endif

#define F first
#define S second
#define read(x) scanf("%d", &x);
#define readln(x) scanf("%d\n", &x);
#define write(x) printf("%d ", x);
#define writeln(x) printf("%d\n", x);
#define forn(i, n) for(int i = 0; i < n; ++i)
#define MEM(x, y) memset(x, y, sizeof(x));
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define runtime clock() * 1.0 / CLOCKS_PER_SEC

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
//typedef pair<int, int> pii;
#define pii pair<int, int>
const ll INF = (1ll << 63) - 1ll;
const ld INFd = 28e14;
const ll inf = (1 << 31) - 1;
const ld EPS = 1e-8;

const ld PI = acos(-1.0);
const ll mod = 7 + 1e9;

using namespace std;

//#include <chrono>
//using namespace std::chrono;
//cerr << "Nanosec:" << duration_cast<nanoseconds>(end_time - start_time).count() << endl;
//time_point<steady_clock> start_time, end_time;
//start_time = high_resolution_clock::now();
//end_time = high_resolution_clock::now();

void OUT(bool f) { if (f) cout << "YES" << endl; else cout << "NO" << endl; }
void Out(bool f) { if (f) cout << "Yes" << endl; else cout << "No" << endl; }
void out(bool f) { if (f) cout << "yes" << endl; else cout << "no" << endl; }

inline int next_rand() { return abs(rand() * rand() + rand()); }

struct __debug__ {
	__debug__(string filename, bool f = false) {
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
		if (filename == "") return;
		ios_base::sync_with_stdio(0);
		cin.tie(0);
		cout.tie(0);
		string filein = filename + ".in";
		string fileout = filename + ".out";
		freopen(filein.c_str(), "r", stdin);
		freopen(fileout.c_str(), "w", stdout);
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
	}
	~__debug__() {
#ifdef _DEBUG
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		cerr << "\n\nTIME: \t" << runtime << endl;
		system("pause");
#endif
	}
};

__debug__ DEBUG("");

//#define STRESS
void gen();
void solve();

//#define GEOM

int main() {
	srand('M' + 'A' + 'S' + 'L' + '0' + 'F');
	srand(time(0));
#ifdef STRESS
	gen();
#endif
	/// zahijoja
	/// aawnrjn6
	/// ugesetacuz
	/// fml31-p08
	/// shop-3
	/// yedetayiro
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	solve();
	//afesivuda
	//ivisuzedu
}
bool dbg = true;
const int maxn = 1000000;
int a[maxn];

ll stress(int l, int r) {
	ll ans = 0;
	for (int i = l; i < r; ++i)
		for (int j = i + 1; j < r; ++j)
			ans += *max_element(a + i, a + j + 1) - *min_element(a + i, a + j + 1);
	return ans;
}

int maxl[maxn];
int maxr[maxn];
int minl[maxn];
int minr[maxn];
ll pmaxl[maxn];
ll pmaxr[maxn];
ll pminl[maxn];
ll pminr[maxn];
int n;

ll askminr(int l, int r) {
	return pminr[r - 1] - pminr[l - 1];
}
ll askmaxr(int l, int r) {
	return pmaxr[r - 1] - pmaxr[l - 1];
}

ll askminl(int l, int r) {
	return pminl[l] - pminl[r];
}
ll askmaxl(int l, int r) {
	return pmaxl[l] - pmaxl[r];
}

void cnt_pref(int l, int r) {
	int m = l + r >> 1;
	if (dbg) {
		for (int i = min(l - 4, 0); i < max(r + 4, n); ++i)
			pminr[i] = pmaxr[i] = pminl[i] = pmaxl[i] = 0;
		//MEM(pminr, 0);
		//MEM(pmaxr, 0);
		//MEM(pminl, 0);
		//MEM(pmaxl, 0);
	}
	pminr[m] = minr[m];
	pmaxr[m] = maxr[m];
	for (int i = m + 1; i < r; ++i) {
		pminr[i] = (pminr[i - 1] + minr[i]);
		pmaxr[i] = (pmaxr[i - 1] + maxr[i]);
	}
	pminl[m - 1] = minl[m - 1];
	pmaxl[m - 1] = maxl[m - 1];
	for (int i = m - 2; i >= l; --i) {
		pminl[i] = (pminl[i + 1] + minl[i]);
		pmaxl[i] = (pmaxl[i + 1] + maxl[i]);
	}
	pmaxl[m] = 0;
	pminl[m] = 0;
}

ll merg(int l = 0, int r = n) {
	if (r - l == 1)return 0;
	int m = l + r >> 1;
	ll ans = merg(l, m) + merg(m, r);
	if (dbg) {
		for (int i = min(l - 4, 0); i < max(r + 4, n); ++i)
			minr[i] = maxr[i] = minl[i] = maxl[i] = 0;
		//MEM(minr, 0);
		//MEM(maxr, 0);
		//MEM(minl, 0);
		//MEM(maxl, 0);
	}
	minr[m] = a[m];
	maxr[m] = a[m];
	for (int i = m + 1; i < r; ++i) {
		minr[i] = min(minr[i - 1], a[i]);
		maxr[i] = max(maxr[i - 1], a[i]);
	}
	minl[m - 1] = a[m - 1];
	maxl[m - 1] = a[m - 1];
	for (int i = m - 2; i >= l; --i) {
		minl[i] = min(minl[i + 1], a[i]);
		maxl[i] = max(maxl[i + 1], a[i]);
	}

	cnt_pref(l, r);

	int L = m;
	int R = m;

	int p = m - 1;

	for (; p >= l; --p) {
		while (L < r && minr[L] >= minl[p])++L;
		while (R < r && maxr[R] <= maxl[p])++R;
		ans += 1ll * (maxl[p] - minl[p]) * (min(L, R) - m);
		if (L == R) {
			ans += askmaxr(R, r) - askminr(L, r);
			continue;
		}
		if (L < R) {
			ans += maxl[p] * (R - L - 0ll) - askminr(L, R);
			ans += askmaxr(R, r) - askminr(R, r);
		}
		else {
			ans += askmaxr(R, L) - minl[p] * (L - R - 0ll);
			ans += askmaxr(L, r) - askminr(L, r);
		}
	}
	//cerr << l << ' ' << r << " = " << ans << " ? " << stress(l, r) << endl;
	return ans;
}

void solve() {
	cin >> n;
	for (int i = 0; i < n; ++i)cin >> a[i];
	cout << merg();
}


#define _CRT_SECURE_NO_DEPRECATE

#pragma warning(disable:4996)
//#pragma comment(linker, "/STACK:512000000")

//190647WR

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <deque>
#include <fstream>
#include <functional>
#include <iterator>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <string>

#define ISO11
#define myDEBUG

#ifdef ISO11
#include <unordered_map>
#include <unordered_set>
#endif

#ifdef myDEBUG

#define assert(x) \
	if(!x){\
		cerr<<"\n\nERROR!\tFailed: "<<x;\
		cerr<<"\nLine: "<<__LINE__;\
		cerr<<"\nFile: "<<__FILE__;\
		cerr<<"\nTime: "<<__TIME__;\
		cerr<<"\nDate: "<<__DATE__;\
	}\

#define err(x) assert(x)
#define warn(x) assert(x)

#endif

#define F first
#define S second
#define read(x) scanf("%d", &x);
#define readln(x) scanf("%d\n", &x);
#define write(x) printf("%d ", x);
#define writeln(x) printf("%d\n", x);
#define forn(i, n) for(int i = 0; i < n; ++i)
#define MEM(x, y) memset(x, y, sizeof(x));
#define mp(x, y) make_pair(x, y)
#define pb(x) push_back(x)
#define runtime clock() * 1.0 / CLOCKS_PER_SEC

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
//typedef pair<int, int> pii;
#define pii pair<int, int>
const ll INF = (1ll << 63) - 1ll;
const ld INFd = 28e14;
const ll inf = (1 << 31) - 1;
const ld EPS = 1e-8;

const ld PI = acos(-1.0);
const ll mod = 7 + 1e9;

using namespace std;

//#include <chrono>
//using namespace std::chrono;
//cerr << "Nanosec:" << duration_cast<nanoseconds>(end_time - start_time).count() << endl;
//time_point<steady_clock> start_time, end_time;
//start_time = high_resolution_clock::now();
//end_time = high_resolution_clock::now();

void OUT(bool f) { if (f) cout << "YES" << endl; else cout << "NO" << endl; }
void Out(bool f) { if (f) cout << "Yes" << endl; else cout << "No" << endl; }
void out(bool f) { if (f) cout << "yes" << endl; else cout << "no" << endl; }

inline int next_rand() { return abs(rand() * rand() + rand()); }

struct __debug__ {
	__debug__(string filename, bool f = false) {
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
		if (filename == "") return;
		ios_base::sync_with_stdio(0);
		cin.tie(0);
		cout.tie(0);
		string filein = filename + ".in";
		string fileout = filename + ".out";
		freopen(filein.c_str(), "r", stdin);
		freopen(fileout.c_str(), "w", stdout);
#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
#endif
	}
	~__debug__() {
#ifdef _DEBUG
		freopen("CON", "r", stdin);
		freopen("CON", "w", stdout);
		cerr << "\n\nTIME: \t" << runtime << endl;
		system("pause");
#endif
	}
};

__debug__ DEBUG("");

//#define STRESS
void gen();
void solve();

//#define GEOM

int main() {
	srand('M' + 'A' + 'S' + 'L' + '0' + 'F');
	srand(time(0));
#ifdef STRESS
	gen();
#endif
	/// zahijoja
	/// aawnrjn6
	/// ugesetacuz
	/// fml31-p08
	/// shop-3
	/// yedetayiro
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	solve();
	//afesivuda
	//ivisuzedu
}

const int maxn = 1000010;
int a[maxn];

ll stress(int l, int r) {
	ll ans = 0;
	for (int i = l; i < r; ++i)
		for (int j = i + 1; j < r; ++j)
			ans += *max_element(a + i, a + j + 1) - *min_element(a + i, a + j + 1);
	return ans;
}

int maxl[maxn];
int maxr[maxn];
int minl[maxn];
int minr[maxn];
ll pmaxl[maxn];
ll pmaxr[maxn];
ll pminl[maxn];
ll pminr[maxn];
int n;

ll askminr(int l, int r) {
	return pminr[r - 1] - pminr[l - 1];
}
ll askmaxr(int l, int r) {
	return pmaxr[r - 1] - pmaxr[l - 1];
}

ll askminl(int l, int r) {
	return pminl[l] - pminl[r];
}
ll askmaxl(int l, int r) {
	return pmaxl[l] - pmaxl[r];
}

void cnt_pref(int l, int r) {
	int m = l + r >> 1;
	pminr[r] = 0;
	pminl[l - 1 >= 0 ? l - 1 : 0] = 0;
	pmaxr[r] = 0;
	pmaxl[l - 1 >= 0 ? l - 1 : 0] = 0;
	pminr[m - 1] = 0;
	pminl[l - 1 >= 0 ? l - 1 : 0] = 0;
	pmaxr[m - 1] = 0;
	pmaxl[l - 2 >= 0 ? l - 2 : 0] = 0;
	//for (int i = min(l - 4, 0); i < max(r + 4, n); ++i)
	//	pminr[i] = pmaxr[i] = pminl[i] = pmaxl[i] = 0;
	pminr[m] = minr[m];
	pmaxr[m] = maxr[m];
	for (int i = m + 1; i < r; ++i) {
		pminr[i] = (pminr[i - 1] + minr[i]);
		pmaxr[i] = (pmaxr[i - 1] + maxr[i]);
	}
	pminl[m - 1] = minl[m - 1];
	pmaxl[m - 1] = maxl[m - 1];
	for (int i = m - 2; i >= l; --i) {
		pminl[i] = (pminl[i + 1] + minl[i]);
		pmaxl[i] = (pmaxl[i + 1] + maxl[i]);
	}
	pmaxl[m] = 0;
	pminl[m] = 0;
}

ll merg(int l = 0, int r = n) {
	if (r - l == 1)return 0;
	int m = l + r >> 1;
	ll ans = merg(l, m) + merg(m, r);
	minr[r] = 0;
	minl[l - 1 >= 0 ? l - 1 : 0] = 0;
	maxr[r] = 0;
	maxl[l - 1 >= 0 ? l - 1 : 0] = 0;
//	for (int i = min(l - 4, 0); i < max(r + 4, n); ++i)
//		minr[i] = maxr[i] = minl[i] = maxl[i] = 0;
	minr[m] = a[m];
	maxr[m] = a[m];
	for (int i = m + 1; i < r; ++i) {
		minr[i] = min(minr[i - 1], a[i]);
		maxr[i] = max(maxr[i - 1], a[i]);
	}
	minl[m - 1] = a[m - 1];
	maxl[m - 1] = a[m - 1];
	for (int i = m - 2; i >= l; --i) {
		minl[i] = min(minl[i + 1], a[i]);
		maxl[i] = max(maxl[i + 1], a[i]);
	}

	cnt_pref(l, r);

	int L = m;
	int R = m;

	int p = m - 1;

	for (; p >= l; --p) {
		while (L < r && minr[L] >= minl[p])++L;
		while (R < r && maxr[R] <= maxl[p])++R;
		ans += 1ll * (maxl[p] - minl[p]) * (min(L, R) - m);
		if (L == R) {
			ans += askmaxr(R, r) - askminr(L, r);
			continue;
		}
		if (L < R) {
			ans += maxl[p] * (R - L - 0ll) - askminr(L, R);
			ans += askmaxr(R, r) - askminr(R, r);
		}
		else {
			ans += askmaxr(R, L) - minl[p] * (L - R - 0ll);
			ans += askmaxr(L, r) - askminr(L, r);
		}
	}
	//cerr << l << ' ' << r << " = " << ans << " ? " << stress(l, r) << endl;
	return ans;
}

void solve() {
	cin >> n;
	for (int i = 0; i < n; ++i)cin >> a[i];
	cout << merg();
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	long long x[100];
	int l;
	void add(long long y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			if (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}

		bool flag=0;
		for (int i=max(l,l2)+1;i>=1;i--) if (x[i]) { l=i;flag=1; break; }
		if (!flag) l=1;
	}
;
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) scanf("%d",&a[i]);
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add((long long)-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add((long long)len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add((long long)-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add((long long)len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.print();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
long long s[1000000+10],s2[1000000+10];
int top,top2;
long long sum,sum2;
long long len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
long long ANS;
int main() {
	cin>>n;
	FOR(i,n) cin>>a[i];
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum-=len[top]*s[top];
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum+=len[top]*s[top];
		while (top2&&s2[top2]<=t) {
			sum2-=len2[top2]*s2[top2];
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2+=len2[top2]*s2[top2];
		//cout<<sum2<<" "<<sum<<endl;
		ANS+=sum2-sum;
	}
	cout<<ANS<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	int x[100],l;
	void add(int y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			if (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}

		bool flag=0;
		for (int i=max(l,l2);i>=1;i--) if (x[i]) { l=i;flag=1; break; }
		if (!flag) l=1;
	}
;
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) cin>>a[i];
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add(-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add(len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add(-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add(len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.print();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	int x[100],l;
	void add(int y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		for (int i=40;i>=1;i--) if (x[i]) { l=i; break; }
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			if (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		for (int i=max(l,l2);i>=1;i--) if (x[i]) { l=i; break; }
	};
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) cin>>a[i];
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add(-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add(len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add(-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add(len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.print();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	long long x[100];
	int l;
	void add(long long y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			//while (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			//while (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}

		bool flag=0;
		for (int i=max(l,l2)+1;i>=1;i--) if (x[i]) { l=i;flag=1; break; }
		if (!flag) l=1;
	};
	void change() {
		FOR(i,l) {
			while (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) scanf("%d",&a[i]);
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add((long long)-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add((long long)len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add((long long)-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add((long long)len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.change();
	ANS.print();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	int x[100],l;
	void add(int y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			if (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}

		bool flag=0;
		for (int i=max(l,l2)+1;i>=1;i--) if (x[i]) { l=i;flag=1; break; }
		if (!flag) l=1;
	}
;
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) cin>>a[i];
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add(-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add(len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add(-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add(len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.print();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	long long x[100];
	int l;
	void add(long long y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			while (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			while (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}

		bool flag=0;
		for (int i=max(l,l2)+1;i>=1;i--) if (x[i]) { l=i;flag=1; break; }
		if (!flag) l=1;
	}
;
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) scanf("%d",&a[i]);
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add((long long)-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add((long long)len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add((long long)-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add((long long)len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.print();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
long long sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
long long ANS;
int main() {
	cin>>n;
	FOR(i,n) cin>>a[i];
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum-=len[top]*s[top];
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum+=len[top]*s[top];
		while (top2&&s2[top2]<=t) {
			sum2-=len2[top2]*s2[top2];
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2+=len2[top2]*s2[top2];
		//cout<<sum2<<" "<<sum<<endl;
		ANS+=sum2-sum;
	}
	cout<<ANS<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for (int i=1;i<=n;i++)

int n;
int a[1000000+10];
int pos[1000000+10];
int s[1000000+10],s2[1000000+10];
int top,top2;
struct bignum {
	long long x[100];
	int l;
	void add(long long y) {
		x[1]+=y;
		for (int i=1;i<=40;i++) {
			x[i+1]+=x[i]/10,x[i]%=10;
		}
		bool flag=0;
		for (int i=40;i>=1;i--) if (x[i]) { l=i; flag=1; break; }
		if (!flag) l=1;
	};
	void add2(bignum y,int sign) {
		int l2=y.l;
		FOR(i,max(l,l2)) {
			x[i]+=sign*y.x[i];
		}
		FOR(i,max(l,l2)) {
			if (x[i]<0) x[i+1]--,x[i]+=10;
			x[i+1]+=x[i]/10,x[i]%=10;
		}

		bool flag=0;
		for (int i=max(l,l2)+1;i>=1;i--) if (x[i]) { l=i;flag=1; break; }
		if (!flag) l=1;
	}
;
	void print() {
		for (int i=l;i>=1;i--) cout<<x[i];
	};
};
bignum sum,sum2;
int len[1000000+10],len2[1000000+10];
int p[1000000+10],p2[1000000+10];
bignum ANS;

int main() {
	cin>>n;
	FOR(i,n) cin>>a[i];
	for (int i=1;i<=n;i++) {

		int t=a[i];
		while (top&&s[top]>=t) {
			sum.add((long long)-len[top]*s[top]);
			top--;
		}
		s[++top]=t;
		if (top>1) len[top]=i-p[top-1];
		else len[top]=i;
		p[top]=i;
		sum.add((long long)len[top]*s[top]);
		while (top2&&s2[top2]<=t) {
			sum2.add((long long)-len2[top2]*s2[top2]);
			top2--;
		}
		s2[++top2]=t;
		if (top2>1) len2[top2]=i-p2[top2-1];
		else len2[top2]=i;
		p2[top2]=i;
		sum2.add((long long)len2[top2]*s2[top2]);
		//cout<<sum2<<" "<<sum<<endl;
		/*
		sum2.print();
		cout<<" ";
		sum.print();
		cout<<endl;*/
		ANS.add2(sum2,1);
		ANS.add2(sum,-1);
		//ANS.print();
		//cout<<endl;
	}
	ANS.print();
	return 0;
}


#include<cstdio>
#include<cstring>
#include<iostream>

#define ll long long
using namespace std;
const int maxn = 1e6+5;
int n;
int l[maxn],r[maxn],a[maxn];
ll output = 0;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        l[i] = r[i] = i;
    }
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]>=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=1;i<n;i++){
        int now=i;
        while(now<n&&a[i]>a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output+=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    for(int i=1;i<=n;i++)
        l[i] = r[i] = i;
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]<=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=1;i<n;i++){
        int now=i;
        while(now<n&&a[i]<a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output-=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    printf("%I64d\n",output);
    return 0;
}


    #include<stdio.h>
    #include<string.h>
    #include<math.h>
    #include<iostream>
    using namespace std;
    #define ll __int64
    int a[1000005];
    int l[1000005];
    int r[1000005];
    int main()
    {
        int n;
        while(~scanf("%d",&n))
        {
            ll output=0;
            for(int i=1;i<=n;i++)scanf("%d",&a[i]);
            for(int i=1;i<=n;i++)l[i]=r[i]=i;
            for(int i=2;i<=n;i++)
            {
                int now=i;
                while(now>1&&a[i]>=a[now-1])now=l[now-1];
                l[i]=now;
            }
            for(int i=n-1;i>=1;i--)
            {
                int now=i;
                while(now<n&&a[i]>a[now+1])now=r[now+1];
                r[i]=now;
            }
            for(int i=1;i<=n;i++)output+=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
            for(int i=1;i<=n;i++)l[i]=r[i]=i;
            for(int i=2;i<=n;i++)
            {
                int now=i;
                while(now>1&&a[i]<=a[now-1])now=l[now-1];
                l[i]=now;
            }
            for(int i=n-1;i>=1;i--)
            {
                int now=i;
                while(now<n&&a[i]<a[now+1])now=r[now+1];
                r[i]=now;
            }
            for(int i=1;i<=n;i++)output-=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
            printf("%I64d\n",output);
        }
    }


#include<stdio.h>
#include<cstring>
#include<iostream>

#define ll long long
#define ll __int64
using namespace std;
const int maxn = 1e6+5;
int n;
int l[maxn],r[maxn],a[maxn];
ll output = 0;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        l[i] = r[i] = i;
    }
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]>=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=1;i<n;i++){
        int now=i;
        while(now<n&&a[i]>a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output+=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    for(int i=1;i<=n;i++)
        l[i] = r[i] = i;
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]<=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=1;i<n;i++){
        int now=i;
        while(now<n&&a[i]<a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output-=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    printf("%I64d\n",output);
    return 0;
}


#include<cstdio>
#include<cstring>
#include<iostream>

#define ll long long
using namespace std;
const int maxn = 1e5+5;
int n;
int l[maxn],r[maxn],a[maxn];
ll output = 0;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        l[i] = r[i] = i;
    }
for(int i=2;i<=n;i++)
        {
            int now=i;
            while(now>1&&a[i]>=a[now-1])now=l[now-1];
            l[i]=now;
        }
        for(int i=n-1;i>=1;i--)
        {
            int now=i;
            while(now<n&&a[i]>a[now+1])now=r[now+1];
            r[i]=now;
        }
        for(int i=1;i<=n;i++)output+=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
        for(int i=1;i<=n;i++)l[i]=r[i]=i;
        for(int i=2;i<=n;i++)
        {
            int now=i;
            while(now>1&&a[i]<=a[now-1])now=l[now-1];
            l[i]=now;
        }
        for(int i=n-1;i>=1;i--)
        {
            int now=i;
            while(now<n&&a[i]<a[now+1])now=r[now+1];
            r[i]=now;
        }
        for(int i=1;i<=n;i++)output-=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
        printf("%I64d\n",output);
    return 0;
}


#include<cstdio>
#include<cstring>
#include<iostream>

#define ll long long
using namespace std;
const int maxn = 1e5+5;
int n;
int l[maxn],r[maxn],a[maxn];
ll output = 0;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        l[i] = r[i] = i;
    }
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]>=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=1;i<n;i++){
        int now=i;
        while(now<n&&a[i]>a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output+=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    for(int i=1;i<=n;i++)
        l[i] = r[i] = i;
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]<=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=1;i<n;i++){
        int now=i;
        while(now<n&&a[i]<a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output-=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
        printf("%I64d\n",output);
    return 0;
}


#include<stdio.h>
#include<cstring>
#include<iostream>

//#define ll long long
#define ll __int64
using namespace std;
const int maxn = 1e6+5;
int n;
int l[maxn],r[maxn],a[maxn];
ll output = 0;

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int i=1;i<=n;i++) l[i] = r[i] = i;
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]>=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=n-1;i>=1;i--){
        int now=i;
        while(now<n&&a[i]>a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output+=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    for(int i=1;i<=n;i++)
        l[i] = r[i] = i;
    for(int i=2;i<=n;i++){
        int now=i;
        while(now>1&&a[i]<=a[now-1]) now = l[now-1];
        l[i] = now;
    }
    for(int i=n-1;i>=1;i--){
        int now=i;
        while(now<n&&a[i]<a[now+1]) now = r[now+1];
        r[i] = now;
    }
    for(int i=1;i<=n;i++)
        output-=(ll)a[i]*(ll)(i-l[i]+1)*(ll)(r[i]-i+1);
    printf("%I64d\n",output);
    return 0;
}


//in the name of Allah
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define F first
#define S second
#define pb push_back

const int inf= 0x77FFFFFF;
const int MX1 = 1000*100+10;
    std::vector<std::pair<ll,ll > > v;
    ll ar[MX1],righ[MX1], lef[MX1];
int main(){
    ll n;
    std::cin>>n;
    for(ll i=0;i<n;i++){
        lef[i] = -1LL;
        righ[i] = n;
    }
    v.clear();
    for(ll i=0;i<n;i++){
        cin>>ar[i];
            //cout<<1<<std::endl;
        while(v.size()&&ar[i]<v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]<=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mn=0;
    for(ll i=0;i<n;i++){
        //cerr<<i<<" "<<abs(righ[i]-i)*abs(lef[i]-i)*ar[i]<<endl;
        mn+=abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }

    v.clear();
    for(ll i=0;i<n;i++){
        lef[i]=-1;
        righ[i]=n;
    }
    for(ll i=0;i<n;i++){
        while(v.size()&&ar[i]>v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]>=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mx=0;
    for(ll i=0;i<n;i++){
        mx+=abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }
    cerr<<mn<<" "<<mx;
    ll ans= mx-mn;
    cout<<ans<<endl;
}


//in the name of Allah
#include <bits/stdc++.h>
#define Init ios_base::sync_with_stdio(0),cin.tie(0)
#define ll long long
#define F first
#define S second
#define pb push_back

const int inf= 0x77FFFFFF;
const int MX1 = 1000*100+10;
using namespace std;
std::vector<std::pair<ll,ll > > v;
ll ar[MX1],righ[MX1], lef[MX1];
int main(){
    Init;
    ll n;
    std::cin>>n;
    for(ll i=0;i<n;i++){
        lef[i] = -1LL;
        righ[i] = n;
    }
    v.clear();
    for(ll i=0;i<n;i++){
        cin>>ar[i];
            //cout<<1<<std::endl;
        while(v.size()&&ar[i]<v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]<=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mn=0;
    for(ll i=0;i<n;i++){
        //cerr<<i<<" "<<abs(righ[i]-i)*abs(lef[i]-i)*ar[i]<<endl;
        mn+=abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }

    v.clear();
    for(ll i=0;i<n;i++){
        lef[i]=-1;
        righ[i]=n;
    }
    for(ll i=0;i<n;i++){
        while(v.size()&&ar[i]>v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]>=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mx=0;
    for(ll i=0;i<n;i++){
        mx+=abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }
    cerr<<mn<<" "<<mx;
    ll ans= mx-mn;
    cout<<ans<<endl;
}


//in the name of Allah
#include <bits/stdc++.h>
#define Init ios_base::sync_with_stdio(0),cin.tie(0)
#define ll long long
#define F first
#define S second
#define pb push_back

const int inf= 0x77FFFFFF;
const int MX1 = 1000*1000+10;
using namespace std;
vector<pair<ll,ll > > v;
ll ar[MX1],righ[MX1], lef[MX1];
int main(){
    Init;
    ll n;
    std::cin>>n;
    for(ll i=0;i<n;i++){
        lef[i] = -1LL;
        righ[i] = n;
    }
    v.clear();
    for(ll i=0;i<n;i++){
        cin>>ar[i];
            //cout<<1<<std::endl;
        while(v.size()&&ar[i]<v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]<=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mn=0;
    for(ll i=0;i<n;i++){
        //cerr<<i<<" "<<abs(righ[i]-i)*abs(lef[i]-i)*ar[i]<<endl;
        mn+=(ll)abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }

    v.clear();
    for(ll i=0;i<n;i++){
        lef[i]=-1;
        righ[i]=n;
    }
    for(ll i=0;i<n;i++){
        while(v.size()&&ar[i]>v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]>=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mx=0;
    for(ll i=0;i<n;i++){
        mx+=(ll)abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }
    cerr<<mn<<" "<<mx;
    ll ans= mx-mn;
    cout<<ans<<endl;
}


//in the name of Allah
#include <bits/stdc++.h>
#define Init ios_base::sync_with_stdio(0),cin.tie(0)
#define ll long long
#define F first
#define S second
#define pb push_back

const int inf= 0x77FFFFFF;
const int MX1 = 1000*100+10;
using namespace std;
vector<pair<ll,ll > > v;
ll ar[MX1],righ[MX1], lef[MX1];
int main(){
    Init;
    ll n;
    std::cin>>n;
    for(ll i=0;i<n;i++){
        lef[i] = -1LL;
        righ[i] = n;
    }
    v.clear();
    for(ll i=0;i<n;i++){
        cin>>ar[i];
            //cout<<1<<std::endl;
        while(v.size()&&ar[i]<v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]<=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mn=0;
    for(ll i=0;i<n;i++){
        //cerr<<i<<" "<<abs(righ[i]-i)*abs(lef[i]-i)*ar[i]<<endl;
        mn+=(ll)abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }

    v.clear();
    for(ll i=0;i<n;i++){
        lef[i]=-1;
        righ[i]=n;
    }
    for(ll i=0;i<n;i++){
        while(v.size()&&ar[i]>v.back().F){
            righ[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    v.clear();
    for(ll i=n-1;i>-1;i--){
        while(v.size()&&ar[i]>=v.back().F){
            lef[v.back().S]=i;
            v.pop_back();
        }
        v.pb({ar[i],i});
    }
    ll mx=0;
    for(ll i=0;i<n;i++){
        mx+=(ll)abs(righ[i]-i)*abs(lef[i]-i)*ar[i];
    }
    cerr<<mn<<" "<<mx;
    ll ans= mx-mn;
    cout<<ans<<endl;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <climits>

using namespace std;
typedef unsigned int index;

template<class Element>/*{{{*/
class PrefixSum
{
private:
	Element *all;
	size_t my_size;
	function<Element (Element, Element)> func, obr_func;
public:
	template<class Iterator>/*{{{*/
	inline PrefixSum(Iterator begin, Iterator end,
			function<Element (Element, Element)> new_func,
			function<Element (Element, Element)> new_obr_func): my_size(0), func(new_func), obr_func(new_obr_func)
	{
		for (Iterator i = begin; i != end; i++)
			my_size++;
		all = new Element[my_size];
		for (index i = 0; i < my_size; i++)
			all[i] = *begin, begin++;
		for (index i = 1; i < my_size; i++)
			all[i] = func(all[i - 1], all[i]);
	}/*}}}*/

	inline Element get(index l, size_t r) const/*{{{*/
	{
		if (l == 0)
			return all[r - 1];
		else
			return obr_func(all[r - 1], all[l - 1]);
	}/*}}}*/

	inline size_t size() const/*{{{*/
	{
		return my_size;
	}/*}}}*/
};/*}}}*/

inline long long get_ans(index l, size_t r, const vector<int> &arr)
{
	if (r - l == 1)
		return 0;
	size_t m = (l + r) / 2;
	long long ans = get_ans(l, m, arr) + get_ans((index)m, r, arr);
	long long cmin = INT_MAX, cmax = INT_MIN;
	vector<pair<long long, long long>> all;
	for (index i = m; i < r; i++)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		all.push_back({cmin, cmax});
	}
	PrefixSum<pair<long long, long long>> ps(all.begin(), all.end(),
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first + b.first, a.second + b.second};},
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first - b.first, a.second - b.second};});
	cmin = INT_MAX, cmax = INT_MIN;
	index yk1 = (index)-1;
	size_t yk2 = 0;
	for (index i = m - 1; i != l - 1; i--)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		while (yk1 + 1 != all.size() and cmin <= all[yk1 + 1].first and cmax >= all[yk1 + 1].second)
			yk1++;
		while (yk2 < all.size() and (cmin <= all[yk2].first or cmax >= all[yk2].second))
			yk2++;
		ans += (cmax - cmin) * (long long)(yk1 + 1);
		if (cmax >= all[yk1 + 1].second)
		{
			ans += cmax * (long long)(yk2 - (yk1 + 1)) - ps.get(yk1 + 1, yk2).first;
		}
		else
		{
			ans += -cmin * (long long)(yk2 - (yk1 + 1)) + ps.get(yk1 + 1, yk2).second;
		}
		ans += ps.get((index)yk2, ps.size()).second - ps.get((index)yk2, ps.size()).first;
	}
	return ans;
}

int main()
{
#ifdef ONPC
	assert(freopen("a.in", "r", stdin));
	assert(freopen("a.out", "w", stdout));
#else
#endif
	ios::sync_with_stdio(false);
	size_t n;
	cin >> n;
	vector<int> a(n);
	for (auto &i: a)
		cin >> i;
	cout << get_ans(0, n, a) << endl;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <climits>

using namespace std;
typedef unsigned int index;

template<class Element>/*{{{*/
class PrefixSum
{
private:
	Element *all;
	size_t my_size;
	function<Element (Element, Element)> func, obr_func;
public:
	template<class Iterator>/*{{{*/
	PrefixSum(Iterator begin, Iterator end,
			function<Element (Element, Element)> new_func,
			function<Element (Element, Element)> new_obr_func): my_size(0), func(new_func), obr_func(new_obr_func)
	{
		for (Iterator i = begin; i != end; i++)
			my_size++;
		all = new Element[my_size];
		for (index i = 0; i < my_size; i++)
			all[i] = *begin, begin++;
		for (index i = 1; i < my_size; i++)
			all[i] = func(all[i - 1], all[i]);
	}/*}}}*/

	Element get(index l, size_t r) const/*{{{*/
	{
		if (l == 0)
			return all[r - 1];
		else
			return obr_func(all[r - 1], all[l - 1]);
	}/*}}}*/

	size_t size() const/*{{{*/
	{
		return my_size;
	}/*}}}*/
};/*}}}*/

long long get_ans(index l, size_t r, const vector<int> &arr)
{
	if (r - l == 1)
		return 0;
	size_t m = (l + r) / 2;
	long long cmin = INT_MAX, cmax = INT_MIN;
	vector<pair<long long, long long>> all;
	for (index i = m; i < r; i++)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		all.push_back({cmin, cmax});
	}
	PrefixSum<pair<long long, long long>> ps(all.begin(), all.end(),
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first + b.first, a.second + b.second};},
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first - b.first, a.second - b.second};});
	cmin = INT_MAX, cmax = INT_MIN;
	index yk1 = (index)-1;
	size_t yk2 = 0;
	long long ans = 0;
	for (index i = m - 1; i != l - 1; i--)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		while (yk1 + 1 != all.size() and cmin <= all[yk1 + 1].first and cmax >= all[yk1 + 1].second)
			yk1++;
		while (yk2 < all.size() and (cmin <= all[yk2].first or cmax >= all[yk2].second))
			yk2++;
		ans += (cmax - cmin) * (long long)(yk1 + 1);
		if (cmax >= all[yk1 + 1].second)
		{
			ans += cmax * (long long)(yk2 - (yk1 + 1)) - ps.get(yk1 + 1, yk2).first;
		}
		else
		{
			ans += -cmin * (long long)(yk2 - (yk1 + 1)) + ps.get(yk1 + 1, yk2).second;
		}
		ans += ps.get((index)yk2, ps.size()).second - ps.get((index)yk2, ps.size()).first;
	}
	return ans + get_ans(l, m, arr) + get_ans((index)m, r, arr);
}

int main()
{
#ifdef ONPC
	assert(freopen("a.in", "r", stdin));
	assert(freopen("a.out", "w", stdout));
#else
#endif
	ios::sync_with_stdio(false);
	size_t n;
	cin >> n;
	vector<int> a(n);
	for (auto &i: a)
		cin >> i;
	cout << get_ans(0, n, a) << endl;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <climits>

using namespace std;
typedef unsigned int index;

template<class Element>/*{{{*/
class PrefixSum
{
private:
	Element *all;
	size_t my_size;
	function<Element (Element, Element)> &func, &obr_func;
public:
	template<class Iterator>/*{{{*/
	inline PrefixSum(Iterator begin, Iterator end,
			function<Element (Element, Element)> new_func,
			function<Element (Element, Element)> new_obr_func): my_size(0), func(new_func), obr_func(new_obr_func)
	{
		for (Iterator i = begin; i != end; i++)
			my_size++;
		all = new Element[my_size];
		for (index i = 0; i < my_size; i++)
			all[i] = *begin, begin++;
		for (index i = 1; i < my_size; i++)
			all[i] = func(all[i - 1], all[i]);
	}/*}}}*/

	inline Element get(index l, size_t r) const/*{{{*/
	{
		if (l == 0)
			return all[r - 1];
		else
			return obr_func(all[r - 1], all[l - 1]);
	}/*}}}*/

	inline size_t size() const/*{{{*/
	{
		return my_size;
	}/*}}}*/
};/*}}}*/

inline long long get_ans(index l, size_t r, const vector<int> &arr)
{
	if (r - l == 1)
		return 0;
	size_t m = (l + r) / 2;
	long long ans = get_ans(l, m, arr) + get_ans((index)m, r, arr);
	long long cmin = INT_MAX, cmax = INT_MIN;
	vector<pair<long long, long long>> all;
	for (index i = m; i < r; i++)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		all.push_back({cmin, cmax});
	}
	PrefixSum<pair<long long, long long>> ps(all.begin(), all.end(),
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first + b.first, a.second + b.second};},
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first - b.first, a.second - b.second};});
	cmin = INT_MAX, cmax = INT_MIN;
	index yk1 = (index)-1;
	size_t yk2 = 0;
	for (index i = m - 1; i != l - 1; i--)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		while (yk1 + 1 != all.size() and cmin <= all[yk1 + 1].first and cmax >= all[yk1 + 1].second)
			yk1++;
		while (yk2 < all.size() and (cmin <= all[yk2].first or cmax >= all[yk2].second))
			yk2++;
		ans += (cmax - cmin) * (long long)(yk1 + 1);
		if (cmax >= all[yk1 + 1].second)
		{
			ans += cmax * (long long)(yk2 - (yk1 + 1)) - ps.get(yk1 + 1, yk2).first;
		}
		else
		{
			ans += -cmin * (long long)(yk2 - (yk1 + 1)) + ps.get(yk1 + 1, yk2).second;
		}
		ans += ps.get((index)yk2, ps.size()).second - ps.get((index)yk2, ps.size()).first;
	}
	return ans;
}

int main()
{
#ifdef ONPC
	assert(freopen("a.in", "r", stdin));
	assert(freopen("a.out", "w", stdout));
#else
#endif
	ios::sync_with_stdio(false);
	size_t n;
	cin >> n;
	vector<int> a(n);
	for (auto &i: a)
		cin >> i;
	cout << get_ans(0, n, a) << endl;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <climits>

using namespace std;
typedef unsigned int index;

template<class Element>/*{{{*/
class PrefixSum
{
private:
	Element *all;
	size_t my_size;
	function<Element (Element, Element)> func, obr_func;
public:
	template<class Iterator>/*{{{*/
	inline PrefixSum(Iterator begin, Iterator end,
			function<Element (Element, Element)> new_func,
			function<Element (Element, Element)> new_obr_func): my_size(0), func(new_func), obr_func(new_obr_func)
	{
		for (Iterator i = begin; i != end; i++)
			my_size++;
		all = new Element[my_size];
		for (index i = 0; i < my_size; i++)
			all[i] = *begin, begin++;
		for (index i = 1; i < my_size; i++)
			all[i] = func(all[i - 1], all[i]);
	}/*}}}*/

	inline Element get(index l, size_t r) const/*{{{*/
	{
		if (l == 0)
			return all[r - 1];
		else
			return obr_func(all[r - 1], all[l - 1]);
	}/*}}}*/

	inline size_t size() const/*{{{*/
	{
		return my_size;
	}/*}}}*/
};/*}}}*/

inline long long get_ans(index l, size_t r, const vector<int> &arr)
{
	if (r - l == 1)
		return 0;
	size_t m = (l + r) / 2;
	long long cmin = INT_MAX, cmax = INT_MIN;
	vector<pair<long long, long long>> all;
	for (index i = m; i < r; i++)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		all.push_back({cmin, cmax});
	}
	PrefixSum<pair<long long, long long>> ps(all.begin(), all.end(),
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first + b.first, a.second + b.second};},
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first - b.first, a.second - b.second};});
	cmin = INT_MAX, cmax = INT_MIN;
	index yk1 = (index)-1;
	size_t yk2 = 0;
	long long ans = 0;
	for (index i = m - 1; i != l - 1; i--)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		while (yk1 + 1 != all.size() and cmin <= all[yk1 + 1].first and cmax >= all[yk1 + 1].second)
			yk1++;
		while (yk2 < all.size() and (cmin <= all[yk2].first or cmax >= all[yk2].second))
			yk2++;
		ans += (cmax - cmin) * (long long)(yk1 + 1);
		if (cmax >= all[yk1 + 1].second)
		{
			ans += cmax * (long long)(yk2 - (yk1 + 1)) - ps.get(yk1 + 1, yk2).first;
		}
		else
		{
			ans += -cmin * (long long)(yk2 - (yk1 + 1)) + ps.get(yk1 + 1, yk2).second;
		}
		ans += ps.get((index)yk2, ps.size()).second - ps.get((index)yk2, ps.size()).first;
	}
	return ans + get_ans(l, m, arr) + get_ans((index)m, r, arr);
}

int main()
{
#ifdef ONPC
	assert(freopen("a.in", "r", stdin));
	assert(freopen("a.out", "w", stdout));
#else
#endif
	ios::sync_with_stdio(false);
	size_t n;
	cin >> n;
	vector<int> a(n);
	for (auto &i: a)
		cin >> i;
	cout << get_ans(0, n, a) << endl;
}


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <climits>

using namespace std;
typedef unsigned int index;

template<class Element>/*{{{*/
class PrefixSum
{
private:
	Element *all;
	size_t my_size;
	function<Element (Element, Element)> &func, &obr_func;
public:
	template<class Iterator>/*{{{*/
	inline PrefixSum(Iterator begin, Iterator end,
			function<Element (Element, Element)> new_func,
			function<Element (Element, Element)> new_obr_func): my_size(0), func(new_func), obr_func(new_obr_func)
	{
		my_size = end - begin;
		all = new Element[my_size];
		for (index i = 0; i < my_size; i++)
			all[i] = *begin, begin++;
		for (index i = 1; i < my_size; i++)
			all[i] = func(all[i - 1], all[i]);
	}/*}}}*/

	inline Element get(index l, size_t r) const/*{{{*/
	{
		if (l == 0)
			return all[r - 1];
		else
			return obr_func(all[r - 1], all[l - 1]);
	}/*}}}*/

	inline size_t size() const/*{{{*/
	{
		return my_size;
	}/*}}}*/
};/*}}}*/

inline long long get_ans(index l, size_t r, const vector<int> &arr)
{
	if (r - l == 1)
		return 0;
	size_t m = (l + r) / 2;
	long long ans = get_ans(l, m, arr) + get_ans((index)m, r, arr);
	long long cmin = INT_MAX, cmax = INT_MIN;
	vector<pair<long long, long long>> all;
	for (index i = m; i < r; i++)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		all.push_back({cmin, cmax});
	}
	PrefixSum<pair<long long, long long>> ps(all.begin(), all.end(),
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first + b.first, a.second + b.second};},
			[](const pair<long long, long long> &a, const pair<long long, long long> &b) -> pair<long long, long long> {return {a.first - b.first, a.second - b.second};});
	cmin = INT_MAX, cmax = INT_MIN;
	index yk1 = (index)-1;
	size_t yk2 = 0;
	for (index i = m - 1; i != l - 1; i--)
	{
		cmin = min(cmin, (long long)arr[i]);
		cmax = max(cmax, (long long)arr[i]);
		while (yk1 + 1 != all.size() and cmin <= all[yk1 + 1].first and cmax >= all[yk1 + 1].second)
			yk1++;
		while (yk2 < all.size() and (cmin <= all[yk2].first or cmax >= all[yk2].second))
			yk2++;
		ans += (cmax - cmin) * (long long)(yk1 + 1);
		if (cmax >= all[yk1 + 1].second)
		{
			ans += cmax * (long long)(yk2 - (yk1 + 1)) - ps.get(yk1 + 1, yk2).first;
		}
		else
		{
			ans += -cmin * (long long)(yk2 - (yk1 + 1)) + ps.get(yk1 + 1, yk2).second;
		}
		ans += ps.get((index)yk2, ps.size()).second - ps.get((index)yk2, ps.size()).first;
	}
	return ans;
}

int main()
{
#ifdef ONPC
	assert(freopen("a.in", "r", stdin));
	assert(freopen("a.out", "w", stdout));
#else
#endif
	ios::sync_with_stdio(false);
	size_t n;
	cin >> n;
	vector<int> a(n);
	for (auto &i: a)
		cin >> i;
	cout << get_ans(0, n, a) << endl;
}


#include<iostream>
#include<cstdio>
#include<math.h>
#include<algorithm>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<queue>
#include<string.h>
#include<cstring>
#include<vector>
#include<time.h>
#include<stdlib.h>
using namespace std;
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
#define FIN freopen("input.txt","r",stdin)
#define mem(x,y) memset(x,y,sizeof(x))
typedef unsigned long long ULL;
typedef long long LL;
#define fuck(x) cout<<"q"<<endl;
#define MX 1111111
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef pair<pair<int,int>,int> PIII;
typedef pair<int,int> PII;
const double eps=1e-8;
int w[MX],n;
int l[MX],r[MX];
int main()
{
    while(cin>>n)
    {
        LL ans=0;
        for(int i=1; i<=n; i++)scanf("%d",&w[i]);
        w[0]=0;
        for(int i=1; i<=n; i++)
        {
            if(w[i-1]<=w[i])l[i]=i;
            else
            {
                l[i]=l[i-1];
                while(w[l[i]-1]>w[i])l[i]--;
            }
        }
        w[n+1]=0;
        for(int i=n; i>=1; i--)
        {
            if(w[i+1]<=w[i])r[i]=i;
            else
            {
                r[i]=r[i+1];
                while(w[r[i]+1]>=w[i])r[i]++;
            }
        }
        for(int i=1; i<=n; i++)
        {
            //cout<<l[i]<<" "<<r[i]<<endl;
            ans-=(LL)w[i]*(i-l[i]+1)*(r[i]-i+1);
        }

        w[0]=INF;
        for(int i=1; i<=n; i++)
        {
            if(w[i-1]>=w[i])l[i]=i;
            else
            {
                l[i]=l[i-1];
                while(w[l[i]-1]<=w[i])l[i]--;
            }
        }
        w[n+1]=INF;
        for(int i=n; i>=1; i--)
        {
            if(w[i+1]>=w[i])r[i]=i;
            else
            {
                r[i]=r[i+1];
                while(w[r[i]+1]<w[i])r[i]++;
            }
        }
        for(int i=1; i<=n; i++)
        {
            ans+=(LL)w[i]*(i-l[i]+1)*(r[i]-i+1);
        }
        cout<<ans<<endl;

    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<math.h>
#include<algorithm>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<queue>
#include<string.h>
#include<cstring>
#include<vector>
#include<time.h>
#include<stdlib.h>
using namespace std;
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
#define FIN freopen("input.txt","r",stdin)
#define mem(x,y) memset(x,y,sizeof(x))
typedef unsigned long long ULL;
typedef long long LL;
#define fuck(x) cout<<"q"<<endl;
#define MX 1111111
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef pair<pair<int,int>,int> PIII;
typedef pair<int,int> PII;
const double eps=1e-8;
int w[MX],n;
int l[MX],r[MX];
inline int read()
{
    int ret=0,c,f=1;
    for(c=getchar(); !(isdigit(c)||c=='-'); c=getchar());
    if(c=='-') f=-1,c=getchar();
    for(; isdigit(c); c=getchar()) ret=ret*10+c-'0';
    if(f<0) ret=-ret;
    return ret;
}
int main()
{
    while(cin>>n)
    {
        LL ans=0;
        for(int i=1; i<=n; i++)w[i]=read();
        w[0]=0;
        for(int i=1; i<=n; i++)
        {
            if(w[i-1]<=w[i])l[i]=i;
            else
            {
                l[i]=l[i-1];
                while(w[l[i]-1]>w[i])l[i]=l[l[i]-1];
            }
        }
        w[n+1]=0;
        for(int i=n; i>=1; i--)
        {
            if(w[i+1]<w[i])r[i]=i;
            else
            {
                r[i]=r[i+1];
                while(w[r[i]+1]>=w[i])r[i]=r[r[i]+1];
            }
        }
        for(int i=1; i<=n; i++)
        {
            //cout<<l[i]<<" "<<r[i]<<endl;
            ans-=(LL)w[i]*(i-l[i]+1)*(r[i]-i+1);
        }

        w[0]=INF;
        for(int i=1; i<=n; i++)
        {
            if(w[i-1]>=w[i])l[i]=i;
            else
            {
                l[i]=l[i-1];
                while(w[l[i]-1]<w[i])l[i]=l[l[i]-1];
            }
        }
        w[n+1]=INF;
        for(int i=n; i>=1; i--)
        {
            if(w[i+1]>w[i])r[i]=i;
            else
            {
                r[i]=r[i+1];
                while(w[r[i]+1]<=w[i])r[i]=r[r[i]+1];
            }
        }
        for(int i=1; i<=n; i++)
        {
            ans+=(LL)w[i]*(i-l[i]+1)*(r[i]-i+1);
        }
        cout<<ans<<endl;

    }
    return 0;
}