Longest Subarray with Constant DifferenceMedium

Longest Subarray with Constant Difference

MediumPractice library · +20 XPtwo pointersgreedyarrays

Given an array A of N integers, find the length of the longest subarray such that the difference between any two adjacent elements in the subarray is constant. A subarray is a contiguous part of the array. For example, in [5, 7, 9, 11], the differences are 7-5=2, 9-7=2, 11-9=2. This subarray has a constant difference of 2.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A_1, A_2, ..., A_N.

Output

Print a single integer, the length of the longest subarray with a constant difference between adjacent elements.

Constraints

1 <= N <= 200000 -10^9 <= A_i <= 10^9

Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
7
1 3 5 7 9 11 13
Output
7

The entire array forms a subarray with a constant difference of 2.

Example 2

Input
8
1 2 3 5 7 9 10 11
Output
4

The longest subarrays are [1, 2, 3] (diff 1) and [5, 7, 9] (diff 2) and [10, 11] (diff 1). The longest is length 3.

Hints