#include <iostream>
#include <cstdio>

#define INF 3073741825
#define NMAX 500005

using namespace std;

long long n , st , dr , ans = -INF , mx;
long long r[NMAX][25] , v[NMAX] , lg[25];

void read(long long &x) {
    int sign = 1;
    char ch;

    while(!isdigit(ch = getchar())) {
        if(ch == '-') {
            sign = -1;
        }

        else {
            sign = 1;
        }
    }

    do {
        x = x * 10 + ch - '0';
    }while(isdigit(ch = getchar()));

    x *= sign;
}

void rmq() {
     for(int i = 1 ; i <= n ; ++i) {
        r[i][0] = v[i];
        for(int j = 1 ; (1 << (j - 1)) <= i ; ++j) {
            r[i][j] = max(r[i - (1 << (j - 1))][j - 1] , r[i][j - 1]);
        }
    }
}

long long query(long long st , long long dr) {
    long long aux = lg[dr - st + 1];
    return max(r[dr][aux] , r[st + (1 << aux) - 1][aux]);
}

int main() {
    #ifndef ONLINE_JUDGE
        freopen("input.txt" , "r" , stdin);
    #endif // ONLINE_JUDGE

    read(n);

    for(int i = 1 ; i <= n ; ++i) {
        read(v[i]);
    }

    rmq();

    for(int i = 1 ; i <= n ; ++i) {
        int aux = 1;
        while((1 << aux) <= i) {
            ++aux;
        }

        lg[i] = aux - 1;
    }

    for(long long i = 1 ; i <= n ; ++i) {
        for(long long j = 1 , nr = 0 ; j < i ; j <<= 1 , ++nr) {
            long long st = max(i - 2 * j + 1 , (long long)1);
            long long dr = i - j;

            mx = -INF;
            mx = query(st , dr);
            ans = max(ans , mx + v[i] - nr);
        }
    }

    cout << ans;
    return 0;
}