#include using namespace std; #define rep(i, x, limit) for (long long i = (long long)x; i < (long long)limit; i++) #define REP(i, x, limit) for (long long i = (long long)x; i <= (long long)limit; i++) #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define el '\n' #define spa " " #define Yes cout << "Yes" << el #define No cout << "No" << el #define YES cout << "YES" << el #define NO cout << "NO" << el #define eps (1e-10) #define Equals(a,b) (fabs((a) - (b)) < eps ) #define debug(x) cerr << #x << " = " << x << el using ll = long long; using ull = unsigned long long; using pii = pair; using pll = pair; using vi = vector; using vl = vector; using vvl = vector>; using vs = vector; using vb = vector; const double pi = 3.141592653589793238; const int inf = 1073741823; const ll infl = 1LL << 60; const string ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string abc = "abcdefghijklmnopqrstuvwxyz"; const ll MOD = 998244353; #include using namespace atcoder; using mint = modint998244353; using vm = vector; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); ll n;cin>>n; vl A(n);rep(i,0,n)cin>>A[i]; stack st; for(auto a:A){ if(st.empty())st.push({a,a}); else{ auto [t,e]=st.top(); if(e==a-1){ st.pop(); st.push({t,a}); }else{ st.push({a,a}); } } } ll ans=0; while(st.size()>1){ auto [aa,bb]=st.top();st.pop(); auto [cc,dd]=st.top();st.pop(); ans+=aa-dd-1; st.push({cc,bb-(aa-dd-1)}); } auto [aa,bb]=st.top();st.pop(); ans+=aa-1; cout<