#C11180. Maximum Subarray with Limited Sum of Absolute Differences

    ID: 40468 Type: Default 1000ms 256MiB

Maximum Subarray with Limited Sum of Absolute Differences

Maximum Subarray with Limited Sum of Absolute Differences

You are given an array of integers and an integer \( k \). Your task is to find the maximum length of a contiguous subarray such that the sum of the absolute differences between every pair of consecutive elements does not exceed \( k \).

In other words, for a subarray \( a[l], a[l+1], \dots, a[r] \), define its cost as

[ S = \sum_{i=l+1}^{r} |a[i] - a[i-1]| ]

You need to determine the maximum possible length \( L = r - l + 1 \) such that \( S \leq k \).

Note: If the array contains only one element, the answer is 1.

This problem can be efficiently solved using a sliding window (two pointers) technique.

inputFormat

The first line of the input contains two integers \( n \) and \( k \) separated by a space, where \( n \) is the number of elements in the array.

The second line contains \( n \) space-separated integers, representing the elements of the array.

Example:

5 3
1 3 7 4 9

outputFormat

Output a single integer representing the maximum length of a subarray such that the sum of the absolute differences between consecutive elements is at most \( k \).

Example:

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