#C13562. Longest Contiguous Subarray with Limited Difference

    ID: 43114 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Limited Difference

Longest Contiguous Subarray with Limited Difference

You are given an array of integers. Your task is to find the length of the longest contiguous subarray such that the absolute difference between any two elements in the subarray is less than or equal to 1. In other words, if max and min represent the maximum and minimum values in the subarray respectively, then the subarray is valid if and only if:

$$ max - min \leq 1 $$

The subarray must be contiguous within the original array.

Example:

  • For the array [1, 2, 2, 3, 4, 4, 5], the longest valid contiguous subarray is [1,2,2] (or any other valid subarray) with a length of 3.

Note: If the array is empty, the answer is 0.

inputFormat

The input is read from stdin and consists of two lines. The first line contains an integer n representing the number of elements in the array. The second line contains n space-separated integers, representing the elements of the array.

If n = 0, the array will be empty.

outputFormat

Output a single integer to stdout which is the length of the longest contiguous subarray where the absolute difference between any two elements is less than or equal to 1.

## sample
7
1 2 2 3 4 4 5
3