Count Non-Decreasing Subarrays After K Operations - Problem

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: 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,5,3], k = 3
Output: 8
💡 Note: Valid subarrays: [4] (0 ops), [2] (0 ops), [5] (0 ops), [3] (0 ops), [4,2] (2 ops: make 2→4), [2,5] (0 ops), [5,3] (2 ops: make 3→5), [2,5,3] (2 ops: make 3→5). Total: 8 subarrays.
Example 2 — No Operations Needed
$ Input: nums = [1,2,3,4], k = 2
Output: 10
💡 Note: Array is already non-decreasing, so all 10 possible subarrays ([1], [1,2], [1,2,3], [1,2,3,4], [2], [2,3], [2,3,4], [3], [3,4], [4]) need 0 operations ≤ 2.
Example 3 — Limited Operations
$ Input: nums = [5,1,3], k = 1
Output: 4
💡 Note: Valid subarrays: [5] (0 ops), [1] (0 ops), [3] (0 ops), [1,3] (0 ops). Subarray [5,1] needs 4 ops (make 1→5), [5,1,3] needs 4 ops, [5,3] needs 2 ops - all exceed k=1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 1012

Visualization

Tap to expand
Count Non-Decreasing Subarrays After K Operations INPUT nums = [4, 2, 5, 3] 4 i=0 2 i=1 5 i=2 3 i=3 k = 3 (max operations) All 10 Subarrays: [4] [2] [5] [3] [4,2] [2,5] [5,3] [4,2,5] [2,5,3] [4,2,5,3] n = 4, Total subarrays = 10 ALGORITHM STEPS 1 Sliding Window Use two pointers (left, right) 2 Check Each Subarray Calculate ops needed 3 Cost Calculation ops = max(0, prev - curr) 4 Count Valid If total ops <= k, count++ Example Calculations: [4,2]: need 2 ops (OK) 2<=3 [2,5]: need 0 ops (OK) 0<=3 [5,3]: need 2 ops (OK) 2<=3 [4,2,5]: need 2 ops (OK) 2<=3 [4,2,5,3]: need 4 ops (X) 4>3 FINAL RESULT Valid Subarrays (8 total): [4] [2] [5] [3] 4 OK [4,2] [2,5] [5,3] 3 OK [4,2,5] 1 OK [2,5,3] needs 2 ops X [4,2,5,3] needs 4 X OUTPUT 8 8 valid subarrays found Key Insight: To make a subarray non-decreasing, we need to increment smaller elements to match or exceed previous ones. For [4,2], we need 2 ops to make 2 become 4. Use sliding window with monotonic stack for O(n) solution. Track cumulative cost and shrink window when cost exceeds k. Each valid window contributes (right-left+1) subarrays. TutorialsPoint - Count Non-Decreasing Subarrays After K Operations | Optimal Solution
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
23.4K Views
Medium-High Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen