inlineintqread(){ char c = getchar(); int x = 0, f = 1; while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + c - 48; c = getchar(); } return x * f; }
typedefunsignedint ui; constint N = 1000005; int n, a[N], pmx[N], smx[N], tmp[N]; ui ans = 0;
inlinevoidRead(){ n = qread(); for (int i = 1;i <= n;i++) a[i] = qread(); }
inlinevoidDnC(int l, int r){ if (l == r) { pmx[l] = a[l] - a[l - 1]; smx[l] = a[l] - a[l + 1]; return; } int mid = l + r >> 1; DnC(l, mid); DnC(mid + 1, r); int i = l, j = mid + 1; while (i <= mid && j <= r) { if (smx[i] <= pmx[j]) { ans += (ui)smx[i] * (ui)(j - mid - 1); i++; } else { ans += (ui)pmx[j] * (ui)(i - l); j++; } } while (i <= mid) { ans += (ui)smx[i] * (ui)(j - mid - 1); i++; } while (j <= r) { ans += (ui)pmx[j] * (ui)(i - l); j++; } int mxv = -0x3f3f3f3f; for (int i = l;i <= mid;i++) mxv = max(mxv, a[i] - max(a[i + 1], a[i - 1])); for (int i = mid + 1;i <= r;i++) pmx[i] = max(pmx[i], mxv); mxv = -0x3f3f3f3f; for (int i = mid + 1;i <= r;i++) mxv = max(mxv, a[i] - max(a[i + 1], a[i - 1])); for (int i = l;i <= mid;i++) smx[i] = max(smx[i], mxv); merge(pmx + l, pmx + mid + 1, pmx + mid + 1, pmx + r + 1, tmp + l); for (int i = l;i <= r;i++) pmx[i] = tmp[i]; merge(smx + l, smx + mid + 1, smx + mid + 1, smx + r + 1, tmp + l); for (int i = l;i <= r;i++) smx[i] = tmp[i]; }
intmain(){ Read(); ans = 0; DnC(1, n); cout << ans << endl; return0; }