Skip to main content

Count Non-Decreasing Subarrays After K Operations - Solution & Explanation

HardArrayStackSegment TreeQueue4 min readAsked at: Microsoft, Google
Practice this problem

Problem Statement

You are given an array nums of n integers and an integer k.

For each subarray of nums, you can apply up to k operations on it. In each operation, you increment any element of the subarray by 1.

Note that each subarray is considered independently, meaning changes made to one subarray do not persist to another.

Return the number of subarrays that you can make non-decreasing ​​​​​after performing at most k operations.

An array is said to be non-decreasing if each element is greater than or equal to its previous element, if it exists.

 

Example 1:

Input: nums = [6,3,1,2,4,4], k = 7

Output: 17

Explanation:

Out of all 21 possible subarrays of nums, only the subarrays [6, 3, 1], [6, 3, 1, 2], [6, 3, 1, 2, 4] and [6, 3, 1, 2, 4, 4] cannot be made non-decreasing after applying up to k = 7 operations. Thus, the number of non-decreasing subarrays is 21 - 4 = 17.

Example 2:

Input: nums = [6,3,1,3,6], k = 4

Output: 12

Explanation:

The subarray [3, 1, 3, 6] along with all subarrays of nums with three or fewer elements, except [6, 3, 1], can be made non-decreasing after k operations. There are 5 subarrays of a single element, 4 subarrays of two elements, and 2 subarrays of three elements except [6, 3, 1], so there are 1 + 5 + 4 + 2 = 12 subarrays that can be made non-decreasing.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 109

Approach Overview

Problem Overview: You are given an array nums and an integer k. A subarray is valid if you can perform at most k increment operations so that the subarray becomes non-decreasing. The task is to count how many subarrays satisfy this condition.

Approach 1: Brute Force Simulation (O(n²) time, O(1) space)

Enumerate every possible subarray starting at index i and extend it to the right. While extending, simulate the minimum increments required to keep the sequence non-decreasing. Maintain the required value for the next element (the maximum seen so far). If nums[j] is smaller, add max_so_far - nums[j] to the operation cost. Stop expanding once the cost exceeds k. This method is easy to reason about and shows how the increment cost accumulates, but checking every subarray leads to O(n²) time.

Approach 2: Sliding Window with Monotonic Stack (O(n) time, O(n) space)

The optimal solution treats the problem as a dynamic window where the right pointer expands the subarray and the left pointer shrinks it when the cost exceeds k. The main challenge is efficiently tracking the number of increments needed to maintain a non-decreasing order. A monotonic stack groups elements into segments where each segment represents values that must be raised to a common height.

When a new element enters the window, merge stack segments while the top value is smaller than the incoming value. Each merge updates the cost required to raise previous elements to the new level. This effectively models the increments needed to maintain a non-decreasing sequence. The stack keeps values in decreasing order so updates happen amortized O(1) per element.

If the accumulated cost exceeds k, move the left boundary of the window forward and remove its contribution from the cost structure. Because each element is pushed and popped at most once from the stack, the total work across the array remains linear. This pattern combines a sliding window with a monotonic structure similar to techniques used in monotonic queue problems.

Every time the window expands to index r, all subarrays ending at r and starting between l and r are valid. Add r - l + 1 to the answer. The algorithm processes the array once and maintains the increment cost dynamically.

Recommended for interviews: Interviewers expect the sliding window combined with a monotonic stack. The brute force approach demonstrates understanding of how increment costs accumulate, but the optimized solution shows strong command of amortized analysis and advanced window techniques.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force SimulationO(n²)O(1)Useful for understanding how increment cost accumulates when forming a non-decreasing sequence.
Sliding Window + Monotonic StackO(n)O(n)Best general solution for large arrays. Maintains increment cost dynamically while expanding and shrinking the window.

Video Solution

3420. Count Non-Decreasing Subarrays After K Operations | Weekly Contest - 432 | Leetcode • Amit Choraria • 1,716 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Count Non-Decreasing Subarrays After K Operations easy or hard?
Count Non-Decreasing Subarrays After K Operations is a Hard problem. It requires combining sliding window logic with a monotonic stack and careful cost accounting, which makes it significantly more complex than standard two-pointer problems.
Count Non-Decreasing Subarrays After K Operations Python/Java solution
Implement the optimal sliding window and monotonic stack approach. Maintain segments representing increasing levels, track the cost of raising elements, and adjust the window when the cost exceeds k. The same logic works in Python, Java, C++, and Go with O(n) complexity.
How to solve Count Non-Decreasing Subarrays After K Operations in O(n)?
Use a sliding window where the right pointer expands the subarray and a monotonic stack tracks segments that must be raised to maintain non-decreasing order. Update the total increment cost when merging segments. If the cost exceeds k, move the left pointer and remove its contribution. Count valid windows as you expand.
What is the best approach for Count Non-Decreasing Subarrays After K Operations?
The optimal approach uses a sliding window combined with a monotonic stack. The window tracks valid subarrays while the stack groups elements that must be raised to maintain a non-decreasing order. This allows efficient updates to the required increment cost and achieves O(n) time complexity.
Is Count Non-Decreasing Subarrays After K Operations asked at Google/Amazon/Meta?
Problems combining sliding window techniques with monotonic stacks frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving subarray counting and amortized data structures are common in senior-level algorithm interviews.
What data structure is used in Count Non-Decreasing Subarrays After K Operations?
The key data structures are a sliding window and a monotonic stack (or deque). The stack stores grouped elements representing levels to which earlier values must be increased, allowing efficient calculation of the required increment cost.
What is the time complexity of Count Non-Decreasing Subarrays After K Operations?
The optimal solution runs in O(n) time with O(n) auxiliary space. Each element is pushed and popped from the monotonic stack at most once, giving amortized constant work per element while the sliding window scans the array.

Ready to solve this problem?

Practice Count Non-Decreasing Subarrays After K Operations with our built-in code editor and test cases.

Practice on FleetCode