#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#include <vector>
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define LONG_LONG_MAX 9223372036854775807LL
#define pblank putchar(' ')
#define ll LL
#define fastIO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> P;
int n, m, k;
const int maxn = 3e5 + 10;
template <class T>
inline T read()
{
    int f = 1;
    T ret = 0;
    char ch = getchar();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (isdigit(ch))
    {
        ret = (ret << 1) + (ret << 3) + ch - '0';
        ch = getchar();
    }
    ret *= f;
    return ret;
}
template <class T>
inline void write(T n)
{
    if (n < 0)
    {
        putchar('-');
        n = -n;
    }
    if (n >= 10)
    {
        write(n / 10);
    }
    putchar(n % 10 + '0');
}
template <class T>
inline void writeln(const T &n)
{
    write(n);
    puts("");
}
vector<int> a;
int l[maxn], r[maxn];
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    // freopen("out.txt","w", stdout);
#endif
    int t = read<int>();
    while (t--)
    {
        n = read<int>();
        a.clear();
        for (int i = 1; i <= n; i++)
            l[i] = 1e9, r[i] = 0;
        for (int i = 1; i <= n; i++)
        {
            int x = read<int>();
            a.emplace_back(x);
            if (l[x] == 1e9)
                l[x] = i;
            r[x] = i;
        }
        sort(a.begin(), a.end());
        a.erase(unique(a.begin(), a.end()), a.end());
        int sz = a.size();
        int res = 1;
        int cur = 1;
        for (int i = 1; i < sz; i++){
            if (l[a[i]] > r[a[i-1]])
                ++cur;
            else
                cur = 1;
            res = max(res, cur);
        }
        writeln(sz-res);
    }
    return 0;
}


#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#include <vector>
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define LONG_LONG_MAX 9223372036854775807LL
#define pblank putchar(' ')
#define ll LL
#define fastIO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> P;
int n, m, k;
const int maxn = 3e5 + 10;
template <class T>
inline T read()
{
    int f = 1;
    T ret = 0;
    char ch = getchar();
    while (!isdigit(ch))
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (isdigit(ch))
    {
        ret = (ret << 1) + (ret << 3) + ch - '0';
        ch = getchar();
    }
    ret *= f;
    return ret;
}
template <class T>
inline void write(T n)
{
    if (n < 0)
    {
        putchar('-');
        n = -n;
    }
    if (n >= 10)
    {
        write(n / 10);
    }
    putchar(n % 10 + '0');
}
template <class T>
inline void writeln(const T &n)
{
    write(n);
    puts("");
}
vector<int> a;
int l[maxn], r[maxn];
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    // freopen("out.txt","w", stdout);
#endif
    int t = read<int>();
    while (t--)
    {
        n = read<int>();
        a.clear();
        for (int i = 1; i <= n; i++)
            l[i] = 1e9, r[i] = 0;
        for (int i = 1; i <= n; i++)
        {
            int x = read<int>();
            a.emplace_back(x);
            if (l[x] == 1e9)
                l[x] = i;
            r[x] = i;
        }
        sort(a.begin(), a.end());
        a.erase(unique(a.begin(), a.end()), a.end());
        int sz = a.size();
        int res = 0;
        for (int i = 1; i < sz; i++)
            if (r[a[i-1]]>l[a[i]])
                ++res;
        writeln(res);
    }
    return 0;
}


#include "bits/stdc++.h"
using namespace std;

long long gcd(long long a,long long b)
{
    if(b==0)
        return a;
    else
        return gcd(b,a%b);
}

long long lcm(long long a,long long b)
{
    return (a*b)/gcd(a,b);
}

int main()
{
    long long i, j, k, te, t, co, x, y, n, m,p, q;
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin>>t;
    for(i=0;i<t;i++)
    {
        vector<long long> v;
        cin>>n;
        for(j=0;j<n;j++)
        {
            cin>>te;
            v.push_back(te);
        }
        set<long long> se;
        co = 0;
        x = 0;
        for(j=0;j<n;j++)
        {
            if(x>v[j] && se.find(v[j])==se.end())
            {
                co++;
                se.insert(v[j]);
            }
            else if(x<=v[j])
            {
                x = v[j];
            }
        }
        cout<<co<<endl;
    }
    return 0;
}


#include "bits/stdc++.h"
using namespace std;

int main()
{
    long long i, j, k, te, t, co, x, y, n, m,p, q;
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin>>t;
    long long con[300005][2];
    long long dp[300005];
    for(i=0;i<t;i++)
    {
        vector<long long> v;
        cin>>n;
        for(j=0;j<n;j++)
        {
            dp[j] = 0;
            con[j][0] =0;
            con[j][1] =0;
            cin>>te;
            v.push_back(te);
        }
        con[j][0] =0;
        con[j][1] =0;
        dp[j] = 0;
        set<long long> se;
        co = 0;
        x = 0;

        for(j=0;j<n;j++)
        {
            if(se.find(v[j])==se.end())
            {
                con[v[j]][0] = j;
                con[v[j]][1] = j;
                se.insert(v[j]);
            }
            else
            {
                con[v[j]][1] = j;
            }
        }
        sort(v.begin(),v.end());
        dp[0] = 1;
        for(j=1;j<n;j++)
        {
            if(v[j]!=v[j-1])
            {
                if(con[v[j-1]][1] < con[v[j]][0])
                    dp[j] = dp[j-1]+1;
                else
                    dp[j] = 1;
            }
            else
            {
                dp[j] = dp[j-1];
            }
        }
        for(j=0;j<n;j++)
        {
            //cout<<dp[j]<<endl;
            if(x<dp[j])
                x = dp[j];
        }
        cout<<se.size()-x<<endl;

    }
    return 0;
}


#include "bits/stdc++.h"
using namespace std;

long long gcd(long long a,long long b)
{
    if(b==0)
        return a;
    else
        return gcd(b,a%b);
}

long long lcm(long long a,long long b)
{
    return (a*b)/gcd(a,b);
}

int main()
{
    long long i, j, k, te, t, co, x, y, n, m,p, q;
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin>>t;
    for(i=0;i<t;i++)
    {
        vector<long long> v;
        cin>>n;
        for(j=0;j<n;j++)
        {
            cin>>te;
            v.push_back(te);
        }
        set<long long> se;
        co = 0;
        x = 0;
        for(j=0;j<n-1;j++)
        {
            if(v[j]>v[j+1] && se.find(v[j+1])==se.end())
            {
                co++;
                se.insert(v[j+1]);
            }
            // else if(v[j]<=v[j+1])
            // {
            //     x = v[j];
            // }
        }
        cout<<co<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> //required
#include <ext/pb_ds/tree_policy.hpp> //required
// iteration and input/output stream
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define srep(i, begin, end) for (__typeof(end) i = begin; i != end; i++)
#define printarr(x) rep(i,0,x.size()) cout<<x[i]<<" "; cout<<endl;

#define tr(cont,it) \
for(decltype(cont.begin()) it = cont.begin(); it!= cont.end() ; it++)

#define tc() int tcase; cin >> tcase ; rep(tc,1,tcase+1)
//STL shortcuts
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define F first
#define S second
#define MP make_pair

// Error detection
#define trace1(x)                cerr<<#x<<": "<<x<<endl
#define trace2(x, y)             cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z)          cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d)       cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e)    cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl

using namespace std;

typedef long long int ll; // 64 bit integer
typedef unsigned long long int  ull; // 64 bit unsigned integer
typedef long double ld;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<int,ll> pill;

inline void smax(int &x , int y) { x = max(x , y) ; }
inline void smin(int &x , int y) { x = min(x , y) ; }

#define MOD 1000000007
#define inf 4000000000000000000LL
#define SYNC std::ios::sync_with_stdio(false);  cin.tie(NULL);
#define N 300001

int main()
{
    SYNC
    vector<vi> indx(N);

    tc()
    {
        int n;
        cin>>n;
        vi v(n);
        vi srt;
        set<int> s;

        rep(i,0,n)
        {
            cin>>v[i];
            indx[v[i]].pb(i);
            s.insert(v[i]);
        }

        tr(s,it)
            srt.pb(*it);

        if(srt.size() == 1)
        {
            rep(i,0,srt.size())
            {
                indx[srt[i] ].clear();
            }
            cout<<0<<"\n";
            continue;
        }

        int l=0,r = 0;
        set<int> indc;
        int ans = 0;

        int cnt =0;
        while(r!= srt.size())
        {
            while(r < srt.size())
            {
                int ad =1;

                int lst = n;
                if(indc.size() > 0)
                {
                    set<int>::iterator it = indc.end();
                    it--;
                    lst = *it;
                }
                else
                {
                    rep(i,0,indx[srt[r] ].size())
                        indc.insert(indx[srt[r] ][i]);
                    r++;
                    continue;
                }

                rep(i,0,indx[srt[r] ].size())
                    if( indx[srt[r] ][i] < lst){ad =0; break; }

                if(ad)
                {
                    rep(i,0,indx[srt[r] ].size())
                        indc.insert(indx[srt[r] ][i]);
                    r++;
                }
                else
                    break;
            }

            //trace2(l,r);
            ans = max(ans,r-l);

            rep(i,0,indx[srt[l] ].size())
                indc.erase(indx[srt[l] ][i]);

            l++;
        }

        rep(i,0,srt.size())
        {
            indx[srt[i] ].clear();
        }
        cout<<srt.size()-ans<<"\n";
    }
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> //required
#include <ext/pb_ds/tree_policy.hpp> //required
// iteration and input/output stream
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define srep(i, begin, end) for (__typeof(end) i = begin; i != end; i++)
#define printarr(x) rep(i,0,x.size()) cout<<x[i]<<" "; cout<<endl;

#define tr(cont,it) \
for(decltype(cont.begin()) it = cont.begin(); it!= cont.end() ; it++)

#define tc() int tcase; cin >> tcase ; rep(tc,1,tcase+1)
//STL shortcuts
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define F first
#define S second
#define MP make_pair

// Error detection
#define trace1(x)                cerr<<#x<<": "<<x<<endl
#define trace2(x, y)             cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z)          cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d)       cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e)    cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl

using namespace std;

typedef long long int ll; // 64 bit integer
typedef unsigned long long int  ull; // 64 bit unsigned integer
typedef long double ld;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<int,ll> pill;

inline void smax(int &x , int y) { x = max(x , y) ; }
inline void smin(int &x , int y) { x = min(x , y) ; }

#define MOD 1000000007
#define inf 4000000000000000000LL
#define SYNC std::ios::sync_with_stdio(false);  cin.tie(NULL);
#define N 300001

int main()
{
    SYNC
    vector<vi> indx(N);

    tc()
    {
        int n;
        cin>>n;
        vi v(n);
        vi srt;
        set<int> s;

        rep(i,0,n)
        {
            cin>>v[i];
            indx[v[i]].pb(i);
            s.insert(v[i]);
        }

        tr(s,it)
            srt.pb(*it);

        if(srt.size() == 1)
        {
            cout<<0<<"\n";
            continue;
        }

        int l=0,r = 0;
        set<int> indc;
        int ans = 0;

        int cnt =0;
        while(r!= srt.size())
        {
            while(r < srt.size())
            {
                int ad =1;

                int lst = n;
                if(indc.size() > 0)
                {
                    set<int>::iterator it = indc.end();
                    it--;
                    lst = *it;
                }
                else
                {
                    rep(i,0,indx[srt[r] ].size())
                        indc.insert(indx[srt[r] ][i]);
                    r++;
                    continue;
                }

                rep(i,0,indx[srt[r] ].size())
                    if( indx[srt[r] ][i] < lst){ad =0; break; }

                if(ad)
                {
                    rep(i,0,indx[srt[r] ].size())
                        indc.insert(indx[srt[r] ][i]);
                    r++;
                }
                else
                    break;
            }

            //trace2(l,r);
            ans = max(ans,r-l);

            rep(i,0,indx[srt[l] ].size())
                indc.erase(indx[srt[l] ][i]);

            l++;
        }

        rep(i,0,srt.size())
        {
            indx[srt[i] ].clear();
        }
        cout<<srt.size()-ans<<"\n";
    }
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> //required
#include <ext/pb_ds/tree_policy.hpp> //required
// iteration and input/output stream
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define srep(i, begin, end) for (__typeof(end) i = begin; i != end; i++)
#define printarr(x) rep(i,0,x.size()) cout<<x[i]<<" "; cout<<endl;

#define tr(cont,it) \
for(decltype(cont.begin()) it = cont.begin(); it!= cont.end() ; it++)

#define tc() int tcase; cin >> tcase ; rep(tc,1,tcase+1)
//STL shortcuts
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define F first
#define S second
#define MP make_pair

// Error detection
#define trace1(x)                cerr<<#x<<": "<<x<<endl
#define trace2(x, y)             cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z)          cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d)       cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e)    cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl

using namespace std;

typedef long long int ll; // 64 bit integer
typedef unsigned long long int  ull; // 64 bit unsigned integer
typedef long double ld;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<int,ll> pill;

inline void smax(int &x , int y) { x = max(x , y) ; }
inline void smin(int &x , int y) { x = min(x , y) ; }

#define MOD 1000000007
#define inf 4000000000000000000LL
#define SYNC std::ios::sync_with_stdio(false);  cin.tie(NULL);
#define N 300001
int n;
vi v;

int main()
{
    SYNC
    tc()
    {
        cin>>n;
        v.resize(n);
        vi srt;
        set<int> s;
        vector<vi> indx(N);
        rep(i,0,n)
        {
            cin>>v[i];
            indx[v[i]].pb(i);
            s.insert(v[i]);
        }

        tr(s,it)
            srt.pb(*it);

        if(srt.size() == 1)
        {
            cout<<0<<"\n";
            continue;
        }

        int l=0,r = 0;
        set<int> indc;
        int ans = 0;
        while(r!= srt.size())
        {
            while(r < srt.size())
            {
                int ad =1;

                int lst = n;
                if(indc.size() > 0)
                {
                    set<int>::iterator it = indc.end();
                    it--;
                    lst = *it;
                }
                else
                {
                    rep(i,0,indx[srt[r] ].size())
                        indc.insert(indx[srt[r] ][i]);
                    r++;
                    continue;
                }

                rep(i,0,indx[srt[r] ].size())
                    if( indx[srt[r] ][i] < lst) ad =0;

                if(ad)
                {
                    rep(i,0,indx[srt[r] ].size())
                        indc.insert(indx[srt[r] ][i]);
                    r++;
                }
                else
                    break;
            }

            //trace2(l,r);
            ans = max(ans,r-l);

            rep(i,0,indx[srt[l] ].size())
                indc.erase(indx[srt[l] ][i]);

            l++;
        }

        cout<<srt.size()-ans<<"\n";
    }
}


#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> //required
#include <ext/pb_ds/tree_policy.hpp> //required
// iteration and input/output stream
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define srep(i, begin, end) for (__typeof(end) i = begin; i != end; i++)
#define printarr(x) rep(i,0,x.size()) cout<<x[i]<<" "; cout<<endl;

#define tr(cont,it) \
for(decltype(cont.begin()) it = cont.begin(); it!= cont.end() ; it++)

#define tc() int tcase; cin >> tcase ; rep(tc,1,tcase+1)
//STL shortcuts
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define F first
#define S second
#define MP make_pair

// Error detection
#define trace1(x)                cerr<<#x<<": "<<x<<endl
#define trace2(x, y)             cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z)          cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d)       cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e)    cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl

using namespace std;

typedef long long int ll; // 64 bit integer
typedef unsigned long long int  ull; // 64 bit unsigned integer
typedef long double ld;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<int,ll> pill;

inline void smax(int &x , int y) { x = max(x , y) ; }
inline void smin(int &x , int y) { x = min(x , y) ; }

#define MOD 1000000007
#define inf 4000000000000000000LL
#define SYNC std::ios::sync_with_stdio(false);  cin.tie(NULL);

vi v;
int n;
int check(int x)
{
    vi tmp(n);
    rep(i,0,n)
    {
        if(v[i] < x)
            tmp[i] = -1;
        else
            tmp[i] = v[i];
    }

    int prv = -1;
    rep(i,0,n)
    {
        if(tmp[i] != -1)
        {
            if(tmp[i] >= prv)
                prv = tmp[i];
            else
                return 0;
        }
    }
    return 1;
}

int main()
{
    SYNC
    tc()
    {
        cin>>n;
        v.resize(n);
        vi srt;
        set<int> s;
        rep(i,0,n)
        {
            cin>>v[i];
            s.insert(v[i]);
        }

        tr(s,it)
        {
            srt.pb(*it);
        }

        int l=0,r = srt.size()-1;
        int ans = srt.size()-1;
        while(l<=r)
        {
            int mid = (l+r)/2;
            int num = srt[mid];
            if(check(num) == 1)
            {
                ans = mid;
                r = mid-1;
            }
            else
                l = mid+1;
        }

        cout<<ans<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX 1000000
int main() {
	// your code goes here
	ll q;
	cin>>q;
	while(q--)
	{
		ll n;
		cin>>n;
		ll a[n];
		ll b[MAX]={0};
		set<ll> s;
		ll k=MAX-1;
		for(ll i=0;i<n;i++)
		{
			cin>>a[i];

		}
		ll c[n+1]={0};
		for(ll i=n-1;i>=0;i--)
		{
			if(c[a[i]]==0)
			{
				b[k]=a[i];
				k--;
				c[a[i]]++;

			}
		}
	//	cout<<MAX-k<<"\n";
	//	k--;
	k++;
	//	cout<<MAX-k<<"\n";
		ll count=0;
	for(ll i=MAX-1;i>=k;i--)
	{
	//	cout<<b[i]<<" ";
	   if(b[i]<b[i-1])
	   count++;
	}
	//cout<<"\n";
	cout<<count<<"\n";

	}
	return 0;
}


import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws IOException {
        init(System.in, System.out);
        int i;
        int n = nextInt();
        long[] a = new long[n];
        for (i = 0; i < n; i++) {
            a[i] = nextLong();
        }
        long[] b = new long[n];
        int aLength = n, bLength = 0;
        boolean hasDuplicate = true, addToB = true;
        while (hasDuplicate) {
            hasDuplicate = false;
            if (addToB) {
                b = new long[aLength];
                bLength = 0;
                for (i = 0; i < aLength-1; i++) {
                    if (a[i] == a[i + 1]) {
                        hasDuplicate = true;
                        b[bLength++] = a[i]+1;
                        i++;
                    } else {
                        b[bLength++] = a[i];
                    }
                }
                if (i == aLength-1) {
                    b[bLength++] = a[i];
                }
                addToB = false;
            } else {
                a = new long[bLength];
                aLength = 0;
                for (i = 0; i < bLength-1; i++) {
                    if (b[i] == b[i + 1]) {
                        hasDuplicate = true;
                        a[aLength++] = b[i]+1;
                        i++;
                    } else {
                        a[aLength++] = b[i];
                    }
                }
                if (i ==bLength-1) {
                    a[aLength++] = b[i];
                }
                addToB = true;
            }
        }
        aLength--;
        bLength--;
        if (addToB) {
            Arrays.sort(a);
            out.write((a[aLength]- aLength) + "\n");
        } else {
            Arrays.sort(b);
            out.write((b[bLength] - bLength) + "\n");
        }
        out.flush();
    }
    private static BufferedReader reader;
    private static BufferedWriter out;
    private static StringTokenizer tokenizer;

    private static void init(InputStream input, OutputStream output) {
        reader = new BufferedReader(new InputStreamReader(input));
        out = new BufferedWriter(new OutputStreamWriter(output));
        tokenizer = new StringTokenizer("");
    }

    private static String next() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    private static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    private static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    private static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map.Entry;

public class C {
    public static int solve(int[] A) {
        HashMap<Integer, Integer> H = new HashMap<Integer, Integer>();
        for (int i = 0; i < A.length;) {
            int j = i;
            while (j < A.length && A[j] == A[i])
                j++;
            int cnt = j - i;
            if (H.containsKey(A[i])) {
                cnt += H.get(A[i]);
                H.remove(A[i]);
            }
            for (int k = 0; k < 32; k++)
                if ((cnt & (1 << k)) != 0) {
                    if (H.containsKey(A[i] + k))
                        H.put(A[i] + k, H.get(A[i] + k) + 1);
                    else
                        H.put(A[i] + k, 1);
                }
            i = j;
        }
        int tot = 0;
        for (Entry<Integer, Integer> e : H.entrySet())
            tot += e.getValue();
        if (tot == H.size()) {
            int[] K = new int[tot + 1];
            K[0] = -1;
            int index = 1;
            for (Entry<Integer, Integer> e : H.entrySet())
                K[index++] = e.getKey();
            Arrays.sort(K);
            int ans = 0;
            for (int i = 1; i < K.length; i++)
                ans += K[i] - K[i - 1] - 1;
            return ans;
        } else {
            int[] K = new int[tot];
            int index = 0;
            for (Entry<Integer, Integer> e : H.entrySet()) {
                int v = e.getValue();
                while (v-- > 0)
                    K[index++] = e.getKey();
            }
            return solve(K);
        }
    }

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        int n = in.readInt();
        int[] A = new int[n];
        for (int i = 0; i < n; i++)
            A[i] = in.readInt();
        System.out.println(solve(A));
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1000];
    private int curChar, numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    private int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private String readLine0() {
        StringBuffer buf = new StringBuffer();
        int c = read();
        while (c != '\n' && c != -1) {
            buf.appendCodePoint(c);
            c = read();
        }
        return buf.toString();
    }

    public String readLine() {
        String s = readLine0();
        while (s.trim().length() == 0)
            s = readLine0();
        return s;
    }

    public String readLine(boolean ignoreEmptyLines) {
        if (ignoreEmptyLines)
            return readLine();
        else
            return readLine0();
    }

    public char readCharacter() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        return (char) c;
    }

    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;

public class C {
    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        int n = in.readInt();
        int[] A = new int[n];
        for (int i = 0; i < n; i++)
            A[i] = in.readInt();
        HashMap<Integer, Integer> H = new HashMap<Integer, Integer>();
        for (int i = 0; i < n;) {
            int j = i;
            while (j < n && A[j] == A[i])
                j++;
            int cnt = j - i;
            if (H.containsKey(A[i])) {
                cnt += H.get(A[i]);
                H.remove(A[i]);
            }
            for (int k = 0; k < 32; k++)
                if ((cnt & (1 << k)) != 0) {
                    if (H.containsKey(A[i] + k))
                        H.put(A[i] + k, H.get(A[i] + k) + 1);
                    else
                        H.put(A[i] + k, 1);
                }
            i = j;
        }
        int[] K = new int[H.size() + 1];
        K[0] = -1;
        int index = 1;
        for (Entry<Integer, Integer> e : H.entrySet())
            K[index++] = e.getKey();
        int ans = 0;
        for (int i = 1; i < K.length; i++)
            ans += K[i] - K[i - 1] - 1;
        System.out.println(ans);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1000];
    private int curChar, numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    private int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private String readLine0() {
        StringBuffer buf = new StringBuffer();
        int c = read();
        while (c != '\n' && c != -1) {
            buf.appendCodePoint(c);
            c = read();
        }
        return buf.toString();
    }

    public String readLine() {
        String s = readLine0();
        while (s.trim().length() == 0)
            s = readLine0();
        return s;
    }

    public String readLine(boolean ignoreEmptyLines) {
        if (ignoreEmptyLines)
            return readLine();
        else
            return readLine0();
    }

    public char readCharacter() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        return (char) c;
    }

    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map.Entry;

public class C {
    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        int n = in.readInt();
        int[] A = new int[n];
        for (int i = 0; i < n; i++)
            A[i] = in.readInt();
        HashMap<Integer, Integer> H = new HashMap<Integer, Integer>();
        for (int i = 0; i < n;) {
            int j = i;
            while (j < n && A[j] == A[i])
                j++;
            int cnt = j - i;
            if (H.containsKey(A[i])) {
                cnt += H.get(A[i]);
                H.remove(A[i]);
            }
            for (int k = 0; k < 32; k++)
                if ((cnt & (1 << k)) != 0) {
                    if (H.containsKey(A[i] + k))
                        H.put(A[i] + k, H.get(A[i] + k) + 1);
                    else
                        H.put(A[i] + k, 1);
                }
            i = j;
        }
        int[] K = new int[H.size() + 1];
        K[0] = -1;
        int index = 1;
        for (Entry<Integer, Integer> e : H.entrySet())
            K[index++] = e.getKey();
        Arrays.sort(K);
        int ans = 0;
        for (int i = 1; i < K.length; i++)
            ans += K[i] - K[i - 1] - 1;
        System.out.println(ans);
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1000];
    private int curChar, numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    private int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    private boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private String readLine0() {
        StringBuffer buf = new StringBuffer();
        int c = read();
        while (c != '\n' && c != -1) {
            buf.appendCodePoint(c);
            c = read();
        }
        return buf.toString();
    }

    public String readLine() {
        String s = readLine0();
        while (s.trim().length() == 0)
            s = readLine0();
        return s;
    }

    public String readLine(boolean ignoreEmptyLines) {
        if (ignoreEmptyLines)
            return readLine();
        else
            return readLine0();
    }

    public char readCharacter() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        return (char) c;
    }

    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
}


import java.util.*;

public class Ci
{
	public static void main (String args[])
	{
		Scanner sc = new Scanner(System.in);
		int k = sc.nextInt();

		long total = 0;
		long count = 0;
		long curr = 0;

		for(int i = 0; i < k; i++)
		{
			long n = sc.nextInt();
			long temp = n - curr;
			curr = n;
			for(int j = 0; j < Math.min(temp,64); j++)
			{
				if(count%2==1) temp--;
				count/=2;
			}
			total+=temp;
			count++;
		}
		while(count > 0)
		{
			if(count%2==0) total++;
			count/=2;
		}
		System.out.println(total);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.NavigableMap;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class Main {
    static void zap() throws IOException {
        int n = nextInt();
        NavigableMap<Integer, Integer> my = new TreeMap<Integer, Integer>();
        for(int i=0;i<n;i++)
        {
            int number = nextInt();
            if(my.containsKey(number))
                my.put(number, my.get(number) + 1);
            else
                my.put(number, 1);
        }
        for(Integer thisKey = my.firstKey(); thisKey != null; thisKey = my.higherKey(thisKey))
        {
            int occur = my.get(thisKey);
            if(occur == 1)
                continue;
            int incrNext = occur / 2;
            if(my.containsKey(thisKey+1))
                my.put(thisKey+1, my.get(thisKey+1) + incrNext);
            else
                my.put(thisKey+1, incrNext);
            if(occur % 2 == 0)
                my.remove(thisKey);
            else
                my.put(thisKey, 1);
        }
        out.println(my.lastKey() + 1 - my.size());
    }

    static BufferedReader br;
    static StringTokenizer st;
    static PrintWriter out;

    public static void main(String[] args) throws IOException {
        InputStream input = System.in;
        br = new BufferedReader(new InputStreamReader(input));
        out = new PrintWriter(System.out);
        zap();
        out.close();
    }

    static long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    static String nextToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = br.readLine();
            if (line == null) {
                return null;
            }
            st = new StringTokenizer(line);
        }
        return st.nextToken();
    }
}


import java.io.*;
import java.util.*;

public class C {

    static void solve() throws IOException {
        int n = nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
        }

        int lastVal = -1;
        int lastCount = 0;
        int hadValues = 0;

        for (int i = 0; i < n; i++) {
            int curVal = a[i];
            int curCount = 1;

            while (lastVal < curVal && lastCount > 0) {
                if ((lastCount & 1) != 0) {
                    ++hadValues;
                }
                ++lastVal;
                lastCount >>>= 1;
            }

            lastCount += curCount;
            lastVal = curVal;

        }

        while (lastCount > 0) {
            if ((lastCount & 1) != 0) {
                ++hadValues;
            }
            ++lastVal;
            lastCount >>>= 1;
        }
        int answer = lastVal - hadValues;
        out.println(answer);
    }

    static BufferedReader br;
    static StringTokenizer st;
    static PrintWriter out;

    public static void main(String[] args) throws IOException {
        InputStream input = System.in;
        PrintStream output = System.out;
        File file = new File("c.in");
        if (file.exists() && file.canRead()) {
            input = new FileInputStream(file);
        }
        br = new BufferedReader(new InputStreamReader(input));
        out = new PrintWriter(output);
        solve();
        out.close();
    }

    static long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    static String nextToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            String line = br.readLine();
            if (line == null) {
                return null;
            }
            st = new StringTokenizer(line);
        }
        return st.nextToken();
    }
}


import java.io.*;
import java.util.*;

public class C {
	FastScanner in;
	PrintWriter out;

	void solve() throws IOException {
		int n = in.nextInt();
		TreeMap<Long, Integer> map = new TreeMap<>();
		for (int i = 0; i < n; i++) {
			long x = in.nextLong();
			if (map.containsKey(x)) {
				map.put(x, map.get(x) + 1);
			} else {
				map.put(x, 1);
			}
		}
		long ans = 0;
		long last = 0;
		while (!map.isEmpty()) {
			long x = map.firstKey();
			int cnt = map.get(x);
			map.remove(x);
			ans += x - last;
			if ((cnt & 1) == 0) {
				++ans;
			}
			last = x + 1;
			if (cnt > 1) {
				if (!map.containsKey(x)) {
					map.put(x + 1, cnt >> 1);
				} else {
					map.put(x + 1, map.get(x + 1) + (cnt >> 1));
				}
			}
		}
		out.println(ans);
	}

	public void run() {
		try {
			InputStream inputStream = System.in;
			File inFile = new File("c.in");
			if (inFile.exists() && inFile.canRead()) {
				inputStream = new FileInputStream(inFile);
			}
			in = new FastScanner(inputStream);
			out = new PrintWriter(System.out);
			solve();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(239);
		}
	}

	private class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		public boolean hasNext() throws IOException {
			while (st == null || !st.hasMoreTokens()) {
				String line = br.readLine();
				if (line == null) {
					return false;
				}
				st = new StringTokenizer(line);
			}
			return true;
		}

		public String next() throws IOException {
			if (hasNext()) {
				return st.nextToken();
			}
			return null;
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}
	}

	public static void main(String[] args) {
		new C().run();
	}
}


import java.io.*;
import java.util.*;

public class C {
	FastScanner in;
	PrintWriter out;

	void solve() throws IOException {
		int n = in.nextInt();
		TreeMap<Long, Integer> map = new TreeMap<>();
		for (int i = 0; i < n; i++) {
			long x = in.nextLong();
			if (map.containsKey(x)) {
				map.put(x, map.get(x) + 1);
			} else {
				map.put(x, 1);
			}
		}
		long ans = 0;
		long last = 0;
		while (!map.isEmpty()) {
			long x = map.firstKey();
			int cnt = map.get(x);
			map.remove(x);
			ans += x - last;
			if ((cnt & 1) == 0) {
				++ans;
			}
			last = x + 1;
			if (cnt > 1) {
				if (!map.containsKey(x + 1)) {
					map.put(x + 1, cnt >> 1);
				} else {
					map.put(x + 1, map.get(x + 1) + (cnt >> 1));
				}
			}
		}
		out.println(ans);
	}

	public void run() {
		try {
			InputStream inputStream = System.in;
			File inFile = new File("c.in");
			if (inFile.exists() && inFile.canRead()) {
				inputStream = new FileInputStream(inFile);
			}
			in = new FastScanner(inputStream);
			out = new PrintWriter(System.out);
			solve();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(239);
		}
	}

	private class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		public boolean hasNext() throws IOException {
			while (st == null || !st.hasMoreTokens()) {
				String line = br.readLine();
				if (line == null) {
					return false;
				}
				st = new StringTokenizer(line);
			}
			return true;
		}

		public String next() throws IOException {
			if (hasNext()) {
				return st.nextToken();
			}
			return null;
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}
	}

	public static void main(String[] args) {
		new C().run();
	}
}


//package contest;

import java.io.*;
import java.util.*;

public class ProblemC {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    int[] readInts() throws IOException {
        String[] strings = reader.readLine().split(" ");
        int[] ints = new int[strings.length];
        for(int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(strings[i]);
        }
        return ints;
    }

    int[] tt = null;
    int ti = 0;
    int readInt() throws IOException {
        if(tt == null || ti == tt.length) {
            tt = readInts();
            ti = 0;
        }
        return tt[ti++];
    }

    long[] readLongs() throws IOException {
        String[] strings = reader.readLine().split(" ");
        long[] ints = new long[strings.length];
        for(int i = 0; i < ints.length; i++) {
            ints[i] = Long.parseLong(strings[i]);
        }
        return ints;
    }

    void solve() throws IOException {
        int n = readInt();
        int[] a = readInts();
        int ans = 0;
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(n);
        for(int x: a) q.add(x);
        int last = -1;
        while(q.size() > 1) {
            int x = q.poll();
            int y = q.poll();
            if(x == y) q.add(x + 1);
            else {
                q.add(y);
                ans += x - last - 1;
                last = x;
            }
        }
        ans += q.peek() - last - 1;
        writer.println(ans);
        writer.flush();
    }

    public static void main(String[] args) throws IOException {
        new ProblemC().solve();
    }
}


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class ProblemC {

	public static void main(String[] args) throws IOException {
		Scanner in = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int n = in.nextInt();
		long[] a = new long[n];
		for (int i = 0; i < n; i++) {
			a[i] = in.nextLong();
		}

		Set<Long> set = new HashSet<Long>();
		for (int i = 0 ; i < n ; i++) {
			long p = a[i];
			while (set.contains(p)) {
				set.remove(p);
				p++;
			}
			set.add(p);
		}

		long max = 0;
		for (long x : set) {
			max = Math.max(max, x);
		}
		out.println(max + 1 - set.size());
		out.flush();
	}

	public static void debug(Object... o) {
		System.err.println(Arrays.deepToString(o));
	}
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class Main {

  int a[], n, arr[], max = 0;
  private void solve() throws IOException {
     n = ni();
     a = nia(n);

     arr = new int[100000];
     for (int i = 0; i < n; ++i) {
       prop(a[i]);
     }

     int res = 0;
     for (int i = max; i >= 0; --i) {
      if (arr[i] == 0)
        ++res;
     }

     prln(res);
   }

  private void prop(int i) {
    while (arr[i] == 1) {
      arr[i] = 0;
      i++;
    }
    arr[i] = 1;
    if (max < i)
      max = i;
  }

   public static void main(String[] args) {
      new Main().run();
   }

   public void run() {
      try {
         if (isFileIO) {
            pw = new PrintWriter(new File("output.out"));
            br = new BufferedReader(new FileReader("input.in"));
         } else {
            pw = new PrintWriter(System.out);
            br = new BufferedReader(new InputStreamReader(System.in));
         }
         solve();
         pw.close();
         br.close();
      } catch (IOException e) {
         System.err.println("IO Error");
      }
   }

   private int[] nia(int n) throws IOException {
      int arr[] = new int[n];
      for (int i = 0; i < n; ++i)
         arr[i] = Integer.parseInt(nextToken());
      return arr;
   }

   private int[] niam1(int n) throws IOException {
      int arr[] = new int[n];
      for (int i = 0; i < n; ++i)
         arr[i] = Integer.parseInt(nextToken()) - 1;
      return arr;
   }

   private long[] nla(int n) throws IOException {
      long arr[] = new long[n];
      for (int i = 0; i < n; ++i)
         arr[i] = Long.parseLong(nextToken());
      return arr;
   }

   private void pr(Object o) {
      pw.print(o);
   }

   private void prln(Object o) {
      pw.println(o);
   }

   private void prln() {
      pw.println();
   }

   int ni() throws IOException {
      return Integer.parseInt(nextToken());
   }

   long nl() throws IOException {
      return Long.parseLong(nextToken());
   }

   double nd() throws IOException {
      return Double.parseDouble(nextToken());
   }

   private String nextToken() throws IOException {
      while (tokenizer == null || !tokenizer.hasMoreTokens()) {
         tokenizer = new StringTokenizer(br.readLine());
      }

      return tokenizer.nextToken();
   }

   // private void qsort(int a[]) {
   // Random rand = new Random(271828182l);
   // qsort(a, 0, a.length, rand);
   // }
   //
   // private void qsort(int a[], int l, int r, Random rand) {
   // if (r - l <= 1)
   // return;
   //
   // if (r - l == 2) {
   // if (a[r - 1] < a[l]) {
   // int t = a[r - 1];
   // a[r - 1] = a[l];
   // a[l] = t;
   // }
   //
   // return;
   // }
   //
   // int x = a[rand.nextInt(r - l) + l];
   // int i = l, j = r - 1;
   // while (i < j) {
   // while (a[i] < x)
   // ++i;
   // while (a[j] > x)
   // --j;
   // if (i < j) {
   // int t = a[i];
   // a[i] = a[j];
   // a[j] = t;
   // ++i;
   // --j;
   // }
   // }
   //
   // qsort(a, l, j + 1, rand);
   // qsort(a, i, r, rand);
   // }

   private BufferedReader br;
   private StringTokenizer tokenizer;
   private PrintWriter pw;
   private final boolean isFileIO = false;
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class Main {

  int a[], n, arr[], max = 0;
  Set<Integer> set;
  private void solve() throws IOException {
     n = ni();
     a = nia(n);

     set = new HashSet<>();
     for (int i = 0; i < n; ++i) {
       prop(a[i]);
     }

     prln(max - set.size() + 1);
   }

  private void prop(Integer i) {
    while (set.contains(i)) {
      set.remove(i);
      ++i;
    }
    set.add(i);
    if (max < i)
      max = i;
  }

   public static void main(String[] args) {
      new Main().run();
   }

   public void run() {
      try {
         if (isFileIO) {
            pw = new PrintWriter(new File("output.out"));
            br = new BufferedReader(new FileReader("input.in"));
         } else {
            pw = new PrintWriter(System.out);
            br = new BufferedReader(new InputStreamReader(System.in));
         }
         solve();
         pw.close();
         br.close();
      } catch (IOException e) {
         System.err.println("IO Error");
      }
   }

   private int[] nia(int n) throws IOException {
      int arr[] = new int[n];
      for (int i = 0; i < n; ++i)
         arr[i] = Integer.parseInt(nextToken());
      return arr;
   }

   private int[] niam1(int n) throws IOException {
      int arr[] = new int[n];
      for (int i = 0; i < n; ++i)
         arr[i] = Integer.parseInt(nextToken()) - 1;
      return arr;
   }

   private long[] nla(int n) throws IOException {
      long arr[] = new long[n];
      for (int i = 0; i < n; ++i)
         arr[i] = Long.parseLong(nextToken());
      return arr;
   }

   private void pr(Object o) {
      pw.print(o);
   }

   private void prln(Object o) {
      pw.println(o);
   }

   private void prln() {
      pw.println();
   }

   int ni() throws IOException {
      return Integer.parseInt(nextToken());
   }

   long nl() throws IOException {
      return Long.parseLong(nextToken());
   }

   double nd() throws IOException {
      return Double.parseDouble(nextToken());
   }

   private String nextToken() throws IOException {
      while (tokenizer == null || !tokenizer.hasMoreTokens()) {
         tokenizer = new StringTokenizer(br.readLine());
      }

      return tokenizer.nextToken();
   }

   // private void qsort(int a[]) {
   // Random rand = new Random(271828182l);
   // qsort(a, 0, a.length, rand);
   // }
   //
   // private void qsort(int a[], int l, int r, Random rand) {
   // if (r - l <= 1)
   // return;
   //
   // if (r - l == 2) {
   // if (a[r - 1] < a[l]) {
   // int t = a[r - 1];
   // a[r - 1] = a[l];
   // a[l] = t;
   // }
   //
   // return;
   // }
   //
   // int x = a[rand.nextInt(r - l) + l];
   // int i = l, j = r - 1;
   // while (i < j) {
   // while (a[i] < x)
   // ++i;
   // while (a[j] > x)
   // --j;
   // if (i < j) {
   // int t = a[i];
   // a[i] = a[j];
   // a[j] = t;
   // ++i;
   // --j;
   // }
   // }
   //
   // qsort(a, l, j + 1, rand);
   // qsort(a, i, r, rand);
   // }

   private BufferedReader br;
   private StringTokenizer tokenizer;
   private PrintWriter pw;
   private final boolean isFileIO = false;
}


import java.util.Scanner;

public class ProblemC {

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        int prev = 0;
        int pc = 0;
        int count = 0;
        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            if (prev != a) {
                for (int j = prev; j < a; j++) {
                    if (pc % 2 == 0) {
                        count++;
                    }
                    pc = pc / 2;
                }
            }
            pc++;
            prev = a;
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.Scanner;

public class ProblemC {

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        int prev = 0;
        int pc = 0;
        int count = 0;
        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            if (prev != a) {
                for (int j = prev; j < a; j++) {
                    if (pc % 2 == 0) {
                        count++;
                    }
                    pc = pc / 2;
                    if (pc == 0) {
                        count += a - j;
                        break;
                    }
                }
            }
            pc++;
            prev = a;
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.Scanner;

public class ProblemC {

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();
        int[] dp = new int[Integer.MAX_VALUE];

        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            dp[a]++;
        }

        for (int i = 0; i < dp.length - 1; i++) {
            if (dp[i] > 1) {
                dp[i + 1] += dp[i] / 2;
                dp[i] = dp[i] % 2;
            }
        }

        boolean start = false;
        int count = 0;
        for (int i = dp.length - 1; i >= 0; i--) {
            if (!start) {
                if (dp[i] != 0)
                    start = true;
            } else {
                if (dp[i] == 0) {
                    count++;
                }
            }
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;

public class ProblemC {
    long[] fact = new long[1000001];

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();
        int[] dp = new int[Integer.MAX_VALUE];

        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            dp[a]++;
        }

        for (int i = 0; i < dp.length - 1; i++) {
            if (dp[i] > 1) {
                dp[i + 1] += dp[i] / 2;
                dp[i] = dp[i] % 2;
            }
        }

        boolean start = false;
        int count = 0;
        for (int i = dp.length - 1; i >= 0; i--) {
            if (!start) {
                if (dp[i] != 0)
                    start = true;
            } else {
                if (dp[i] == 0) {
                    count++;
                }
            }
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.Scanner;

public class ProblemC {

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        int prev = 0;
        int pc = 0;
        int count = 0;
        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            if (prev != a) {
                for (int j = prev; j < a; j++) {
                    if (pc % 2 == 0) {
                        count++;
                    }
                    pc = pc / 2;
                    if (pc == 0) {
                        count += a - j - 1;
                        break;
                    }
                }
            }
            pc++;
            prev = a;
        }

        while (pc > 0) {
            if (pc % 2 == 0) {
                count++;
            }
            pc = pc / 2;
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;

public class ProblemC {
    long[] fact = new long[1000001];

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();
        int[] dp = new int[10020];

        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            dp[a]++;
        }

        for (int i = 0; i < dp.length - 1; i++) {
            if (dp[i] > 1) {
                dp[i + 1] += dp[i] / 2;
                dp[i] = dp[i] % 2;
            }
        }

        boolean start = false;
        int count = 0;
        for (int i = dp.length - 1; i >= 0; i--) {
            if (!start) {
                if (dp[i] != 0)
                    start = true;
            } else {
                if (dp[i] == 0) {
                    count++;
                }
            }
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.Scanner;

public class ProblemC {

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        int prev = 0;
        int pc = 0;
        int count = 0;
        for (int i = 0; i < n; i++) {
            int a = scan.nextInt();
            if (prev != a) {
                for (int j = prev; j < a; j++) {
                    if (pc % 2 == 0) {
                        count++;
                    }
                    pc = pc / 2;
                    if (pc == 0) {
                        count += a - j - 1;
                        break;
                    }
                }
            }
            pc++;
            prev = a;
        }

        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class ProblemC {
    long[] fact = new long[1000001];

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        for (int i = 0; i < n; i++) {
            Long b = scan.nextLong();
            if (!map.containsKey(b)) {
                map.put(b, 0);
            }
            map.put(b, map.get(b) + 1);
        }

        boolean fin = false;
        while (!fin) {
            for (Long key : map.keySet()) {
                fin = true;
                int c = map.get(key);
                if (c > 1) {
                    fin = false;
                    map.put(key, c % 2);
                    if (!map.containsKey(key + 1)) {
                        map.put(key + 1, 0);
                    }
                    map.put(key + 1, map.get(key + 1) + c / 2);
                }
            }
        }

        ArrayList<Long> list = new ArrayList<Long>();
        list.addAll(map.keySet());
        Collections.shuffle(list);
        Collections.sort(list);

        long prev = -1;
        long count = 0;
        for (Long l : list) {
            count += (l - prev - 1);
            prev = l;
        }
        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class ProblemC {
    long[] fact = new long[1000001];

    public void solve() {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        HashMap<Long, Integer> map = new HashMap<Long, Integer>();
        for (int i = 0; i < n; i++) {
            Long b = scan.nextLong();
            if (!map.containsKey(b)) {
                map.put(b, 0);
            }
            map.put(b, map.get(b) + 1);
        }

        boolean fin = false;
        while (!fin) {
            for (Long key : map.keySet()) {
                fin = true;
                int c = map.get(key);
                if (c > 1) {
                    fin = false;
                    map.put(key, c % 2);
                    if (!map.containsKey(key + 1)) {
                        map.put(key + 1, 0);
                    }
                    map.put(key + 1, map.get(key + 1) + (c / 2));
                }
            }
        }

        ArrayList<Long> list = new ArrayList<Long>();

        for (Long key : map.keySet()) {
            if (map.get(key) > 0) {
                list.add(key);
            }
        }

        Collections.shuffle(list);
        Collections.sort(list);

        long prev = -1;
        long count = 0;
        for (Long l : list) {
            count += (l - prev - 1);
            prev = l;
        }
        System.out.println(count);
    }

    public static void main(String[] args) {
        ProblemC c = new ProblemC();
        c.solve();
    }
}


import java.awt.Point;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class C {
	public static void main(String[] args) throws Exception {
		int cnt = nextInt();
		int[] ar = new int[cnt];
		for (int i = 0; i < cnt; i++) {
			ar[i] = nextInt();
		}
		TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
		ArrayList<Point> entries = new ArrayList<Point>();
		for (int i = 0; i < cnt; i++) {
			int prev = ar[i];
			int cur = prev;
			int eqCnt = 1;
			int j = i + 1;
			while (j < cnt) {
				cur = ar[j];
				if (cur == prev) {
					eqCnt++;
				} else
					break;
				j++;
			}
			entries.add(new Point(prev, eqCnt));
			i = j - 1;
		}
		Collections.sort(entries, new Comparator<Point>() {
			public int compare(Point p1, Point p2) {
				return new Integer(p1.x).compareTo(p2.x);
			}
		});
		int exist = 0;
		int maxPower = 0;
		for (int i = 0; i < entries.size(); i++) {
			Point point = entries.get(i);
			if (map.size() > 0) {
				if (map.firstKey() < point.x) {
					Entry<Integer, Integer> e = map.pollFirstEntry();
					point = new Point(e.getKey(), e.getValue());
					i--;
				} else if (map.firstKey() == point.x) {
					Entry<Integer, Integer> e = map.pollFirstEntry();
					point.y += e.getValue();
				}
			}
			if (point.y >= 1) {
				int val = point.y;
				while (val > 1) {
					int j = 1;
					int power = point.x - 1;
					for (; j <= val; j <<= 1) {
						power++;
					}
					j >>= 1;
					val -= j;
					if (map.containsKey(power)) {
						map.put(power, map.get(power) + 1);
					} else {
						map.put(power, 1);
					}
				}
				if (val == 1) {
					maxPower = Math.max(maxPower, point.x);
					exist++;
				}
			}
			if (i == entries.size() - 1) {
				while (!map.isEmpty()) {
					Entry<Integer, Integer> e = map.pollFirstEntry();
					entries.add(new Point(e.getKey(), e.getValue()));
				}
			}
		}
		System.out.println(maxPower + 1 - exist);
	}

	static BufferedReader br = new BufferedReader(new InputStreamReader(
			System.in));
	static StringTokenizer st = new StringTokenizer("");

	static int nextInt() throws Exception {
		return Integer.parseInt(next());
	}

	static String next() throws Exception {
		while (true) {
			if (st.hasMoreTokens()) {
				return st.nextToken();
			}
			String s = br.readLine();
			if (s == null) {
				return null;
			}
			st = new StringTokenizer(s);
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

public class IvanAndPowersOfTwo {
	public static void main(String[] args) {
		MyScanner sc = new MyScanner();

		int N = sc.nextInt();

		long[] arr = new long[N];
		for (int i = 0; i < N; i++) {
			arr[i] = sc.nextLong();
		}

		long max = 0;
		BinCountSet bsc = new BinCountSet();
		for (int i = 0; i < N; i++) {
			long A = arr[i];
			long v = bsc.insert(A);
			max = Math.max(max, v);
		}
		for (int t = 1; t < 4; t++) {
			bsc = new BinCountSet();
			for (int i = 0; i < N; i++) {
				long A = arr[i];
				long v = bsc.insert(A);
				max = Math.max(max, v);
			}
		}
		System.out.println(max - bsc.size() + 1);
	}

	public static class BinCountSet extends HashSet<Long> {
		private static final long serialVersionUID = 2492877876671495810L;

		public long insert(long k) {
			if (this.contains(k)) {
				this.remove(k);
				return this.insert(k + 1);
			} else {
				this.add(k);
				return k;
			}
		}
	}

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		String nextLine() {
			String str = "";
			try { str = br.readLine(); }
			catch (IOException e) { e.printStackTrace(); }
			return str;
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

public class IvanAndPowersOfTwo {
	public static void main(String[] args) {
		MyScanner sc = new MyScanner();

		int N = sc.nextInt();

		long max = 0;
		BinCountSet bsc = new BinCountSet();
		for (int i = 0; i < N; i++) {
			long A = sc.nextLong();
			long v = bsc.insert(A);
			max = Math.max(max, v);
		}
		System.out.println(max - bsc.size() + 1);
	}

	public static class BinCountSet extends HashSet<Long> {
		private static final long serialVersionUID = 2492877876671495810L;

		public long insert(long k) {
			if (this.contains(k)) {
				this.remove(k);
				return this.insert(k + 1);
			} else {
				this.add(k);
				return k;
			}
		}
	}

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		String nextLine() {
			String str = "";
			try { str = br.readLine(); }
			catch (IOException e) { e.printStackTrace(); }
			return str;
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

public class IvanAndPowersOfTwo {
	public static void main(String[] args) {
		MyScanner sc = new MyScanner();

		int N = sc.nextInt();

		long[] arr = new long[N];
		for (int i = 0; i < N; i++) {
			arr[i] = sc.nextLong();
		}

		long max = 0;
		BinCountSet bsc = new BinCountSet();
		for (int i = 0; i < N; i++) {
			long A = arr[i];
			long v = bsc.insert(A);
			max = Math.max(max, v);
		}
		for (int t = 1; t < 21; t++) {
			bsc = new BinCountSet();
			for (int i = 0; i < N; i++) {
				long A = arr[i];
				long v = bsc.insert(A);
				max = Math.max(max, v);
			}
		}
		System.out.println(max - bsc.size() + 1);
	}

	public static class BinCountSet extends HashSet<Long> {
		private static final long serialVersionUID = 2492877876671495810L;

		public long insert(long k) {
			if (this.contains(k)) {
				this.remove(k);
				return this.insert(k + 1);
			} else {
				this.add(k);
				return k;
			}
		}
	}

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		String nextLine() {
			String str = "";
			try { str = br.readLine(); }
			catch (IOException e) { e.printStackTrace(); }
			return str;
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

public class IvanAndPowersOfTwo {
	public static void main(String[] args) {
		MyScanner sc = new MyScanner();

		int N = sc.nextInt();

		long max = 0;
		BinCountSet bsc = new BinCountSet();
		for (int i = 0; i < N; i++) {
			long A = sc.nextLong();
			long v = bsc.insert(A);
			max = Math.max(max, v);
		}
		for (int t = 1; t < 4; t++) {
			bsc = new BinCountSet();
			for (int i = 0; i < N; i++) {
				long A = sc.nextLong();
				long v = bsc.insert(A);
				max = Math.max(max, v);
			}
		}
		System.out.println(max - bsc.size() + 1);
	}

	public static class BinCountSet extends HashSet<Long> {
		private static final long serialVersionUID = 2492877876671495810L;

		public long insert(long k) {
			if (this.contains(k)) {
				this.remove(k);
				return this.insert(k + 1);
			} else {
				this.add(k);
				return k;
			}
		}
	}

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		String nextLine() {
			String str = "";
			try { str = br.readLine(); }
			catch (IOException e) { e.printStackTrace(); }
			return str;
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

public class IvanAndPowersOfTwo {
	public static void main(String[] args) {
		MyScanner sc = new MyScanner();

		int N = sc.nextInt();

		long[] arr = new long[N];
		for (int i = 0; i < N; i++) {
			arr[i] = sc.nextLong();
		}

		long max = 0;
		BinCountSet bsc = new BinCountSet();
		for (int i = 0; i < N; i++) {
			long A = arr[i];
			long v = bsc.insert(A);
			max = Math.max(max, v);
		}
		System.out.println(max - bsc.size() + 1);
	}

	public static class BinCountSet extends HashSet<Long> {
		private static final long serialVersionUID = 2492877876671495810L;

		public long insert(long k) {
			if (this.contains(k)) {
				this.remove(k);
				return this.insert(k + 1);
			} else {
				this.add(k);
				return k;
			}
		}
	}

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		String next() {
			while (st == null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		String nextLine() {
			String str = "";
			try { str = br.readLine(); }
			catch (IOException e) { e.printStackTrace(); }
			return str;
		}
	}
}


import java.io.InputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.HashSet;

public class IvanAndPowersOfTwo {
	public static void main(String[] args) {
		FasterScanner sc = new FasterScanner();

		int N = sc.nextInt();

		long[] arr = new long[N];
		for (int i = 0; i < N; i++) {
			arr[i] = sc.nextLong();
		}

		long max = 0;
		BinCountSet bsc = new BinCountSet();
		for (int i = 0; i < N; i++) {
			long A = arr[i];
			long v = bsc.insert(A);
			max = Math.max(max, v);
		}
		System.out.println(max - bsc.size() + 1);
	}

	public static class BinCountSet extends HashSet<Long> {
		private static final long serialVersionUID = 2492877876671495810L;

		public long insert(long k) {
			if (this.contains(k)) {
				this.remove(k);
				return this.insert(k + 1);
			} else {
				this.add(k);
				return k;
			}
		}
	}

	public static class FasterScanner {
		private InputStream mIs;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FasterScanner() {
			this(System.in);
		}

		public FasterScanner(InputStream is) {
			mIs = is;
		}

		public int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = mIs.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

	    public long[] nextLongArray(int n) {
	        long[] arr = new long[n];
	        for (int i = 0; i < n; i++) {
	            arr[i] = nextLong();
	        }
	        return arr;
	    }

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

	    public int[] nextIntArray(int n) {
	        int[] arr = new int[n];
	        for (int i = 0; i < n; i++) {
	            arr[i] = nextInt();
	        }
	        return arr;
	    }

		public boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

	}
}


//package threadpractice;
//import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
//import java.math.BigInteger;

public class Main {

    //public static int count;
    public static void main(String args[]) {
        try {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String s[] = br.readLine().split(" ");
        HashMap<Long,Integer> hm = new HashMap();
        int c = 1;

        long prev = Long.parseLong(s[0]);
        Long max = prev;
        for(int i = 1;i<n;i++){
            long current = Long.parseLong(s[i]);
            if(prev==current){
                c++;
            }
            else{
                long next = prev;
                //System.out.println(next+" "+hm);
                if(hm.containsKey(next)){
                    hm.remove(next);
                    c++;
                }
                while(c!=0){
                    if(max<next){
                    max = next;
                }
                if(c%2==0){
                    next++;c = c/2;
                }
                else{
                    hm.put(next,1);
                    c = c/2;
                    next++;
                }

                }
               c = 1;
            }

            prev = current;
        }
        long next = prev;
                if(hm.containsKey(next)){
                    hm.remove(next);
                    c++;
                }
                while(c!=0){
                    if(max<next){
                    max = next;
                }
                if(c%2==0){
                    next++;c = c/2;
                }
                else{
                    hm.put(next,1);
                    c = c/2;
                    next++;
                }

                }
                //System.out.println(hm);
        System.out.println(max+1-hm.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   }


//package threadpractice;
//import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
//import java.math.BigInteger;

public class Main {

    //public static int count;
    public static void main(String args[]) {
        try {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String s[] = br.readLine().split(" ");
        HashMap<Long,Integer> hm = new HashMap();
        int c = 1;

        long prev = Long.parseLong(s[0]);
        Long max = prev;
        for(int i = 1;i<n;i++){
            long current = Long.parseLong(s[i]);
            if(prev==current){
                c++;
            }
            else{
                long next = prev;

                while(c!=0){
                    if(hm.containsKey(next)){
                    hm.remove(next);
                    c++;
                }
                    if(max<next){
                    max = next;
                }
                if(c%2==0){
                    next++;c = c/2;
                }
                else{
                    hm.put(next,1);
                    c = c/2;
                    next++;
                }

                }
                //System.out.println(next+" "+hm);
               c = 1;
            }

            prev = current;
        }
        long next = prev;

                while(c!=0){
                    if(hm.containsKey(next)){
                    hm.remove(next);
                    c++;
                }
                    if(max<next){
                    max = next;
                }
                if(c%2==0){
                    next++;c = c/2;
                }
                else{
                    hm.put(next,1);
                    c = c/2;
                    next++;
                }

                }
                //System.out.println(next+" "+hm);
                //System.out.println(hm);
        System.out.println(max+1-hm.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   }


import java.io.*;
import java.util.*;
public final class powers_of_two
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Map<Integer,Integer> m1=new HashMap<Integer,Integer>();

	static int get(int val)
	{
		return ((m1.get(val)==null)?0:m1.get(val));
	}

	static void put(int num,int val)
	{
		if(m1.get(num)==null)
		{
			m1.put(num,1);
		}
		else
		{
			m1.put(num,m1.get(num)+val);
		}
	}

	public static void main(String args[]) throws Exception
	{
		int n=sc.nextInt();
		for(int i=0;i<n;i++)
		{
			int val=sc.nextInt();put(val,1);
			while(get(val)==2)
			{
				put(val,-2);
				put(val+1,1);
				val++;
			}
		}
		//out.println(m1);
		int max=-1;
		for(Map.Entry<Integer,Integer> curr:m1.entrySet())
		{
			int key=curr.getKey(),val=curr.getValue();
			if(val>0)
			{
				max=Math.max(max,key);
			}
		}
		int res=0;
		for(Map.Entry<Integer,Integer> curr:m1.entrySet())
		{
			int key=curr.getKey(),val=curr.getValue();
			if(key<=max && val>0)
			{
				res++;
			}
		}
		out.println(max+1-res);out.close();
	}
}
class FastScanner
{
    BufferedReader in;
    StringTokenizer st;

    public FastScanner(BufferedReader in) {
        this.in = in;
    }

    public String nextToken() throws Exception {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

	public String next() throws Exception {
		return nextToken().toString();
	}

    public int nextInt() throws Exception {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws Exception {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }
}


import java.io.*;
import java.util.*;

public class C {
  public static void main(String[] args){
    FastScanner sc = new FastScanner();
    int n = sc.nextInt();
    int[] a = new int[n];
    for(int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
    }

    long result = 0;
    int currentA = 0;
    int numA = 0;
    for(int ai : a) {
      if(currentA != ai) {
        while(numA > 0 && currentA < ai) {
          if(numA % 2 == 0) result++;
          numA /= 2;
          currentA++;
        }
        result += ai - currentA;
        numA++;
        currentA = ai;
      } else {
        numA++;
      }
    }

    while(numA > 0) {
      if(numA % 2 == 0) result++;
      numA /= 2;
    }
    System.out.println(result);
  }

  public static class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(String s) {
      try {
        br = new BufferedReader(new FileReader(s));
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }

    public FastScanner() {
      br = new BufferedReader(new InputStreamReader(System.in));
    }

    String nextToken() {
      while (st == null || !st.hasMoreElements()) try {
        st = new StringTokenizer(br.readLine());
      } catch (IOException e) {
        e.printStackTrace();
      }
      return st.nextToken();
    }

    int nextInt() {
      return Integer.parseInt(nextToken());
    }

    long nextLong() {
      return Long.parseLong(nextToken());
    }

    double nextDouble() {
      return Double.parseDouble(nextToken());
    }
  }
}


import java.io.*;
import java.util.*;

public class C {
  public static void main(String[] args){
    FastScanner sc = new FastScanner();
    int n = sc.nextInt();
    int[] a = new int[n];
    for(int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
    }

    long result = 0;
    int currentA = 0;
    int numA = 0;
    for(int ai : a) {
      if(currentA != ai) {
        while(numA > 0 && currentA < ai) {
          if(numA % 2 == 0) result++;
          numA /= 2;
          currentA++;
        }
        result += ai - currentA;
        numA = 1;
        currentA = ai;
      } else {
        numA++;
      }
    }

    while(numA > 0) {
      if(numA % 2 == 0) result++;
      numA /= 2;
    }
    System.out.println(result);
  }

  public static class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner(String s) {
      try {
        br = new BufferedReader(new FileReader(s));
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }

    public FastScanner() {
      br = new BufferedReader(new InputStreamReader(System.in));
    }

    String nextToken() {
      while (st == null || !st.hasMoreElements()) try {
        st = new StringTokenizer(br.readLine());
      } catch (IOException e) {
        e.printStackTrace();
      }
      return st.nextToken();
    }

    int nextInt() {
      return Integer.parseInt(nextToken());
    }

    long nextLong() {
      return Long.parseLong(nextToken());
    }

    double nextDouble() {
      return Double.parseDouble(nextToken());
    }
  }
}


import static java.lang.System.*;
import static java.lang.Math.*;

import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;

public class C305 {
    public static Scanner sc=new Scanner(in);
    //public static Random sc=new Random();

    void run() {
        final int n=sc.nextInt();
        int[] as=new int[n];
        for(int i = 0; i < n; i++) as[i]=sc.nextInt();

        int tcnt=0,tmax=0;
        for(int i=0;i<n;){
            int j =i;
            while (j+1 < n && as[i]==as[j+1]) j++;
            int cnt=j-i+1;
            if (cnt % 2 == 1){// is 1
                tcnt++;
                if (as[i] > tmax) tmax = as[i];
                i++;
            }
            // carry up
            cnt/=2;
            i += cnt;
            for(int k = j; k>j-cnt;k--) as[k]++;
        }
        ln(tmax-tcnt+1);
    }

    public static void main(String[] args) {
        new C305().run();
    }

    //output lib
    static final String br=System.getProperty("line.separator");
    static final String[] asep=new String[]{""," ",br,br+br};

    static String str(Object o){
        int depth=_getArrayDepth(o);
        return depth>0?_strArray(o,depth):o.toString();
    }
    @Deprecated
    static int _getArrayDepth(Object o){
        if(!o.getClass().isArray() || Array.getLength(o)==0) return 0;
        return  1+_getArrayDepth(Array.get(o,0));
    }
    @Deprecated
    private static String _strArray(Object o,int depth){
        if(depth==0) return str(o);
        StringBuilder sb=new StringBuilder();
        for(int i=0,len=Array.getLength(o);i<len;i++){
            if(i!=0)sb.append(asep[depth]);
            sb.append(_strArray(Array.get(o,i),depth-1));
        }
        return sb.toString();
    }

    public static void pr(Object obj){
        out.print(str(obj));
    }
    public static void ln(){
        out.println();
    }
    public static void ln(Object... obj){
        for(Object o:obj){
            pr(o);ln();
        }
    }
}


import static java.lang.System.*;
import static java.lang.Math.*;

import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;

public class C305 {
    public static Scanner sc=new Scanner(in);
    //public static Random sc=new Random();

    void run() {
        final int n=sc.nextInt();
        ArrayList<Long> as=new ArrayList<>();
        for(int i=0;i<n;i++)
            as.add(sc.nextLong());

        Collections.sort(as);

        //calc
        for(int i=0;i<as.size();i++){
            long v=as.get(i);
            int dup=1;
            for(int j=i+1;j<as.size();j++){
                if(as.get(j)!=v)break;
                dup++;
            }
            if(dup>1){
                for(int j=i;j<i+dup;j++){
                    as.remove(i);//i times add
                }
                for(int j=0;j<dup/2;j++){
                    as.add(i,v+1);//1/2 times add
                }
                if(dup%2==1)as.add(i,v);
            }
        }

        //get
        long pos=-1;
        int res=0;
        for(int i=0;i<as.size();i++){
            long v=as.get(i);
            res+=v-pos-1;
            pos=v;
        }
        ln(res);
    }

    public static void main(String[] args) {
        new C305().run();
    }

    //output lib
    static final String br=System.getProperty("line.separator");
    static final String[] asep=new String[]{""," ",br,br+br};

    static String str(Object o){
        int depth=_getArrayDepth(o);
        return depth>0?_strArray(o,depth):o.toString();
    }
    @Deprecated
    static int _getArrayDepth(Object o){
        if(!o.getClass().isArray() || Array.getLength(o)==0) return 0;
        return  1+_getArrayDepth(Array.get(o,0));
    }
    @Deprecated
    private static String _strArray(Object o,int depth){
        if(depth==0) return str(o);
        StringBuilder sb=new StringBuilder();
        for(int i=0,len=Array.getLength(o);i<len;i++){
            if(i!=0)sb.append(asep[depth]);
            sb.append(_strArray(Array.get(o,i),depth-1));
        }
        return sb.toString();
    }

    public static void pr(Object obj){
        out.print(str(obj));
    }
    public static void ln(){
        out.println();
    }
    public static void ln(Object... obj){
        for(Object o:obj){
            pr(o);ln();
        }
    }
}


import static java.lang.System.*;
import static java.lang.Math.*;

import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;

public class C305 {
    public static Scanner sc=new Scanner(in);
    //public static Random sc=new Random();

    void run() {
        final int n=sc.nextInt();
        LinkedList<Long> as=new LinkedList<>();
        for(int i=0;i<n;i++)
            as.add(sc.nextLong());

        //calc
        for(int i=0;i<as.size();i++){
            long v=as.get(i);
            int dup=1;
            for(int j=i+1;j<as.size();j++){
                if(as.get(j)!=v)break;
                dup++;
            }
            for(int j=i;j<i+dup;j++){
                as.remove(i);//i回消す
            }
            for(int j=0;j<dup/2;j++){
                as.add(v+1);//1/2個足す
            }
            if(dup%2==1)as.add(v);
            Collections.sort(as);
        }

        //get
        long pos=-1;
        int res=0;
        for(int i=0;i<as.size();i++){
            long v=as.get(i);
            res+=v-pos-1;
            pos=v;
        }
        ln(res);
    }

    public static void main(String[] args) {
        new C305().run();
    }

    //output lib
    static final String br=System.getProperty("line.separator");
    static final String[] asep=new String[]{""," ",br,br+br};

    static String str(Object o){
        int depth=_getArrayDepth(o);
        return depth>0?_strArray(o,depth):o.toString();
    }
    @Deprecated
    static int _getArrayDepth(Object o){
        if(!o.getClass().isArray() || Array.getLength(o)==0) return 0;
        return  1+_getArrayDepth(Array.get(o,0));
    }
    @Deprecated
    private static String _strArray(Object o,int depth){
        if(depth==0) return str(o);
        StringBuilder sb=new StringBuilder();
        for(int i=0,len=Array.getLength(o);i<len;i++){
            if(i!=0)sb.append(asep[depth]);
            sb.append(_strArray(Array.get(o,i),depth-1));
        }
        return sb.toString();
    }

    public static void pr(Object obj){
        out.print(str(obj));
    }
    public static void ln(){
        out.println();
    }
    public static void ln(Object... obj){
        for(Object o:obj){
            pr(o);ln();
        }
    }
}