#include <iostream>
#include <map>
#define int long long
using namespace std;

int32_t main()
{
    int n,as=0,S=0,d=1;
    cin>>n;
    int s[n+1];
    map<int,int>mp;
    for(int i=1;i<=n;i++)
    {
        cin>>s[i];
        mp[s[i]]++;
    }
    for(int i=n;i>=1;i-=d)
    {
        if(s[i]>as)
        {
            S+=(s[i]-as)*(mp[s[i]]);
            as+=mp[s[i]];
            //cout<<S<<' '<<s[i]<<endl;
        }
        d=mp[s[i]];
    }
    cout<<S;
    return 0;
}
