![]() |
VOOZH | about |
Longest Equal Subarray with at Most K IncrementsLongest Equal Subarray with at Most K IncrementsGiven an array arr[] and an integer k, find the maximum length subarray whose elements can be made equal using at most k increments. An element can be incremented multiple times, but the total number of increments must not exceed k.
Examples:
Input: arr[] = [2, 4, 8, 5, 9, 6], k = 6
Output: 3
Explanation: Subarray [8, 5, 9] can be changed to [9, 9, 9] with 5 increments, which is within the limit k = 6.Input: arr[] = [2, 2, 4], k = 10
Output: 3
Explanation: Entire array can be made [4, 4, 4] using 4 increments, well within the allowed k = 10.Input: arr[] = [1, 2, 3, 4], k = 2
Output: 2
Explanation: Subarrays [1, 2], [2, 3], and [3, 4] can each be converted into equal elements using 1 increment.
Table of Content
Generate all possible subarrays and for each subarray, find its maximum element as the target and calculate the total increments required. If the required increments do not exceed k, update the maximum length.
3
The idea is based on the fact that if we maintain sum of elements and max in a window, then we can count the number of increments in O(1) time using maxElement * windowSize - windowSum. So we maintain a sliding window with these parameters. To track the maximum of every window size, we use a monotonic (decreasing order) deque.
3