VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-length-of-subarray-of-equal-elements-by-performing-at-most-k-increment-operations/

⇱ Longest Equal Subarray with at Most K Increments - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Equal Subarray with at Most K Increments

Last Updated : 7 Apr, 2026

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.

[Naive Approach] Generate and Check All Subarrays - O(n^3) Time and O(1) Space

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.

  • Initialize maxLength as 1 to store the answer.
  • Use two loops to generate all subarrays [i...j].
  • For each subarray, find its max element as the target.
  • Compute total increments needed to match this target.
  • If increments ≤ k, update maxLength.
  • Return the final max length.

Output
3

[Expected Approach] Sliding Window with Deque - O(n) Time and O(n) Space

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.

  • Use two pointers (left, right) to maintain a sliding window and keep track of the sum.
  • Maintain a monotonic decreasing deque to get the maximum element.
  • Compute cost = maxElement * window_size - sum.
  • If cost exceeds k, shrink the window from the left and update the deque.
  • Track and return the maximum valid window length.

Output
3
Comment