#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000005;
const int INF = 1 << 30;
struct Node {
  unsigned long long sum[2];
  int w[2], cv[2], sz, h;
  Node *lc, *rc;
  Node() {}
  Node(int a, int b, int c) : sz(1), h(c), lc(0), rc(0) {
    cv[0] = cv[1] = 0;
    w[0] = sum[0] = a;
    w[1] = sum[1] = b;
  }
  inline void update() {
    for (int k = 0; k < 2; k++)
      sum[k] = (lc ? lc->sum[k] : 0) + (rc ? rc->sum[k] : 0) + w[k];
    sz = (lc ? lc->sz : 0) + (rc ? rc->sz : 0) + 1;
  }
  inline void cover(int a, int b) {
    if (a != 0) w[0] = a, cv[0] = a, sum[0] = (unsigned long long)(a)*sz;
    if (b != 0) w[1] = b, cv[1] = b, sum[1] = (unsigned long long)(b)*sz;
  }
  inline void down() {
    if (lc) lc->cover(cv[0], cv[1]);
    if (rc) rc->cover(cv[0], cv[1]);
    cv[0] = cv[1] = 0;
  }
} *root = 0, *nil = 0;
Node *merge(Node *a, Node *b) {
  if (!a) return b;
  if (!b) return a;
  if (a->h < b->h) {
    a->down();
    a->rc = merge(a->rc, b), a->update();
    return a;
  } else {
    b->down();
    b->lc = merge(a, b->lc), b->update();
    return b;
  }
}
inline bool cmp(Node *p, int k, bool ch) {
  if (ch)
    return p->w[1] <= k;
  else
    return p->w[0] >= k;
}
pair<Node *, Node *> split(Node *p, int k, bool ch) {
  if (!p) return make_pair(nil, nil);
  p->down();
  if (cmp(p, k, ch)) {
    pair<Node *, Node *> y = split(p->rc, k, ch);
    p->rc = y.first, p->update();
    return make_pair(p, y.second);
  } else {
    pair<Node *, Node *> y = split(p->lc, k, ch);
    p->lc = y.second, p->update();
    return make_pair(y.first, p);
  }
}
unsigned long long res = 0;
int a[MAXN];
int n;
int main() {
  ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) {
    pair<Node *, Node *> y = make_pair(nil, nil);
    if (i > 1 && a[i] > a[i - 1]) {
      y = split(root, a[i], 0);
      y.second->cover(a[i], 0);
      root = merge(y.first, y.second);
    } else if (i > 1 && a[i] < a[i - 1]) {
      y = split(root, a[i], 1);
      y.second->cover(0, a[i]);
      root = merge(y.first, y.second);
    }
    res += (root ? root->sum[0] : 0) - (root ? root->sum[1] : 0);
    root = merge(root, new Node(a[i], a[i], rand()));
  }
  cout << res << endl;
  return 0;
}
