#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const long long DIM = 1e5 + 7, INF = 1e9 + 7;

int a[DIM];
vector<int> ixs;
unordered_map<int, int> place;

int main()
{
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  //freopen("./input.txt", "r", stdin);

  int n, k, curr_i, moved = 0, ans = 0;
  cin >> n;

  for (int i = 0; i < n; i++)
  {
    cin >> k;
    if (place[k] == 0)
    {
      ixs.push_back(k);
      place[k] = ixs.size();
    }

    a[place[k]]++;
  }

  curr_i = ixs.size() - 1;

  while (ixs.size())
  {
    int curr = ixs[curr_i];

    ans += (curr - moved) * a[place[curr]];
    moved += a[place[curr]];

    ixs.erase(ixs.end() - 1);
    curr_i--;
    while (ixs[0] <= moved && ixs.size())
      ixs.erase(ixs.begin());
  }

  cout << ans << '\n';

  return 0;
}
