#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long n, a[200005];
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
  vector<vector<long long>> last;
  for (int i = n - 1; i >= 0; --i) {
    long long cnt = 1, stool = 0;
    while (last.size() && last.back()[0] < a[i]) {
      cnt += last.back()[1];
      stool = last.back()[2] + last.back()[1] * (a[i] - last.back()[0]);
      last.pop_back();
    }
    last.push_back({a[i], cnt, stool});
  }
  long long ans = 0;
  for (auto k : last) {
    ans += k[2];
  }
  cout << ans << "\n";
}
