#include <bits/stdc++.h>
#include<iostream>
using namespace std;
 
int main() {
    int a,b,c,d,ans,tmp,max;
    string s;
 
    a = b = c = d = ans = tmp = 0;
    

    cin >> a;
    vector<int>x(a);
  	for(int i =0;i < a;i++){
      cin >> x[i];
    }
  
    tmp = x.size()-1;
    for(int i = tmp;i > 2;i--){
      
      max = *std::max_element(0, x.end()-d);
      if(x[i] < max){
        ans += max = x[i];
      }
      d++;
    }
   cout << ans;
}
