#include<iostream>
using namespace  std;

int broiChisla;

int chisla[5010];

int vtoroNaiGOtDo[5010][5010];

int main(){

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

    cin>>broiChisla;

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

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

        for(int 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;
        }

    }

    int otgovor = 0;

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

            otgovor = max(otgovor, tuka);
        }
    }

    cout<<otgovor<<endl;

    return 0;
}
