#include <iostream>
#include <set>

#define endl  '\n'

using namespace std;

const int MAXN = 1e6 + 3;
int nums[MAXN];

int slow_sol(int n)
{
    int res = -1;
    multiset<int> biggest;

    for (int l = 0; l < n - 1; ++l)
    {
        biggest.clear();
        biggest.insert(nums[l]);

        for (int r = l + 1; r < n; ++r) {
            biggest.insert(nums[r]);

            auto it = --biggest.end();
            res = max(res, *(--it) - (r - l + 1));
        }
    }

    return res;
}

int fast_sol(int n)
{
    int max1_value = nums[0], max1_ind = 0;
    int max2_value = nums[1], max2_ind = 1;

    pair<int, int> max1 = {nums[0], 0};
    pair<int, int> max2 = {nums[1], 1};

    if (nums[0] <= nums[1])
    {
        swap(max1, max2);
    }

    int res = max2.first - 2;

    int l = 0;
    for (int r = 2; r < n; ++r)
    {
        if (nums[r] > max1.first) {
            max2 = max1;
            max1 = {nums[r], r};

            l = max2.second;
        }
        else if (nums[r] > max2.first)
        {
            max2 = {nums[r], r};

            l = max1.second;
        }
        else if (nums[r] == max2.first)
        {
            if (nums[r] == max1.first)
            {
                l = max(max1.second, max2.second);
                max2.second = l;
                max1.second = r;
            }
            else
            {
                l = max1.second;
                max2.second = r;
            }
        }

        res = max(res, max2.first - (r - l + 1));

        // cout << "(" << l << ", " << r << ")  -> " << max2.first << " " << res << endl;
    }

    return res;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

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

    cout << slow_sol(n) << endl;

    return 0;
}
