#include <iostream>

#define endl  '\n'

using namespace std;

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

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

    int n;
    cin >> n;

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

    if (n == 1)
    {
        cout << 0 << endl;
        return 0;
    }

    int l = 0;
    int max1 = max(nums[0], nums[1]);
    int max2 = min(nums[0], nums[1]);
    int res = max2 - 2;

    for (int r = 2; r < n; ++r)
    {
        if (nums[r] > max1) {
            max2 = max1;
            max1 = nums[r];

            while (nums[l] != max2)
            {
                ++l;
            }
        }
        else if (nums[r] > max2)
        {
            max2 = nums[r];

            while (nums[l] != max1)
            {
                ++l;
            }
        }

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

    cout << res << endl;

    return 0;
}
