#include<iostream>
using namespace  std;

long long broiChisla;

long long chisla[5010];

long long vtoroNaiGOtDo[5010][5010];

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    cin>>broiChisla;

    for(long long i = 0; i < broiChisla; i++){
        cin>>chisla[i];
    }


    for(long long i = 0; i < broiChisla - 1; i++){
        long long naiGolqmoto = chisla[i];
        long long vtorotoGolqmo = 0;

        for(long long j = i + 1; j < broiChisla; j++){
            if(chisla[j] > naiGolqmoto){
                vtorotoGolqmo = naiGolqmoto;
                naiGolqmoto = chisla[j];
            }else{
                if(chisla[j] >= vtorotoGolqmo){
                    vtorotoGolqmo = chisla[j];
                }
            }

            vtoroNaiGOtDo[i][j] = vtorotoGolqmo;
        }

    }

    long long otgovor = -1000000010;

    for(long long i = 0; i < broiChisla - 1; i++){
        for(long long j = i + 1; j < broiChisla; j++){
            long long tuka = vtoroNaiGOtDo[i][j] - (j - i + 1);

            otgovor = max(otgovor, tuka);
        }
    }

    cout<<otgovor<<endl;


    /*
    int otgvor = 0;

    for(int i = 0; i < broiChisla; i++){
        for(int j = i + 1; j < broiChisla; j++){
            int naiGolqmoto = 0;
            int vtorotoGolqmo = 0;
            for(int k = i; k <= j; k++){
                if(chisla[k] > naiGolqmoto){
                    vtorotoGolqmo = naiGolqmoto;
                    naiGolqmoto = chisla[k];
                }else{
                    if(chisla[k] > vtorotoGolqmo){
                        vtorotoGolqmo = chisla[k];
                    }
                }

                otgvor = max(otgvor, vtor)
            }
        }
    }
    */

    return 0;
}
