#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,a[300005],l[300005],r[300005],kq = 0;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
freopen("DIFERENCIJA.inp", "r", stdin);
freopen("DIFERENCIJA.out", "w", stdout);
cin >> n;
memset(l,0,sizeof(l));
memset(r,0,sizeof(r));
for(int i = 1; i <= n; i++)
{
cin >> a[i];
}
for(int i = 1; i <= n; i++)
{
l[i] = i - 1;
while(l[i] > 0 && a[l[i]] >= a[i]) l[i] = l[l[i]];
}
for(int i = n; i >= 1; i--)
{
r[i] = i + 1;
while(r[i] <= n && a[r[i]] > a[i]) r[i] = r[r[i]];
}
for(int i = 1; i <= n; i++)
kq -= a[i]*(i - l[i])*(r[i] - i);
for(int i = 1; i <= n; i++)
{
l[i] = i - 1;
while(l[i] > 0 && a[l[i]] <= a[i]) l[i] = l[l[i]];
}
for(int i = n; i >= 1; i--)
{
r[i] = i + 1;
while(r[i] <= n && a[r[i]] < a[i]) r[i] = r[r[i]];
}
for(int i = 1; i <= n; i++)
kq += a[i]*(i - l[i] )*(r[i] - i);
cout << kq;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2RlZmluZSBsbCBsb25nIGxvbmcKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKbGwgbixhWzMwMDAwNV0sbFszMDAwMDVdLHJbMzAwMDA1XSxrcSA9IDA7CmludCBtYWluKCkKewogICAgaW9zX2Jhc2U6OnN5bmNfd2l0aF9zdGRpbygwKTsgY2luLnRpZSgwKTsgY291dC50aWUoMCk7CiAgICBmcmVvcGVuKCJESUZFUkVOQ0lKQS5pbnAiLCAiciIsIHN0ZGluKTsKICAgIGZyZW9wZW4oIkRJRkVSRU5DSUpBLm91dCIsICJ3Iiwgc3Rkb3V0KTsKICAgIGNpbiA+PiBuOwogICAgbWVtc2V0KGwsMCxzaXplb2YobCkpOwogICAgbWVtc2V0KHIsMCxzaXplb2YocikpOwogICAgZm9yKGludCBpID0gMTsgaSA8PSBuOyBpKyspCiAgICB7CiAgICAgICAgY2luID4+IGFbaV07CiAgICB9CiAgICBmb3IoaW50IGkgPSAxOyBpIDw9IG47IGkrKykKICAgIHsKICAgICAgICBsW2ldID0gaSAtIDE7CiAgICAgICAgd2hpbGUobFtpXSA+IDAgJiYgYVtsW2ldXSA+PSBhW2ldKSBsW2ldID0gbFtsW2ldXTsKICAgIH0KICAgIGZvcihpbnQgaSA9IG47IGkgPj0gMTsgaS0tKQogICAgewogICAgICAgIHJbaV0gPSBpICsgMTsKICAgICAgICB3aGlsZShyW2ldIDw9IG4gJiYgYVtyW2ldXSA+IGFbaV0pIHJbaV0gPSByW3JbaV1dOwogICAgfQogICAgZm9yKGludCBpID0gMTsgaSA8PSBuOyBpKyspCiAgICAgICBrcSAtPSBhW2ldKihpIC0gbFtpXSkqKHJbaV0gLSBpKTsKICAgIGZvcihpbnQgaSA9IDE7IGkgPD0gbjsgaSsrKQogICAgewogICAgICAgIGxbaV0gPSBpIC0gMTsKICAgICAgICB3aGlsZShsW2ldID4gMCAmJiBhW2xbaV1dIDw9IGFbaV0pIGxbaV0gPSBsW2xbaV1dOwogICAgfQogICAgZm9yKGludCBpID0gbjsgaSA+PSAxOyBpLS0pCiAgICB7CiAgICAgICAgcltpXSA9IGkgKyAxOwogICAgICAgIHdoaWxlKHJbaV0gPD0gbiAmJiBhW3JbaV1dIDwgYVtpXSkgcltpXSA9IHJbcltpXV07CiAgICB9CiAgICBmb3IoaW50IGkgPSAxOyBpIDw9IG47IGkrKykKICAgIGtxICs9IGFbaV0qKGkgLSBsW2ldICkqKHJbaV0gLSBpKTsKICAgIGNvdXQgPDwga3E7Cn0K