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: nums=[4,2,5,3], k=34253Example: Subarray [4,2] → [4,4] needs 2 operations ≤ 3 ✓Valid Subarrays (operations ≤ 3):[4]:0, [2]:0, [5]:0, [3]:0, [4,2]:2, [2,5]:0, [5,3]:2, [2,5,3]:2Invalid: [4,2,5]:2, [4,2,5,3]:4, [4,5]:0, [4,5,3]:2 (some exceed k or miscounted)Correct count: 8 valid subarraysResult: 8 subarrays can be made non-decreasing with ≤ 3 operations
Understanding the Visualization
1
Input
Array [4,2,5,3] with k=3 operations allowed per subarray
2
Process
For each subarray, calculate minimum operations to make non-decreasing
3
Output
Count of subarrays that need ≤ k operations
Key Takeaway
🎯 Key Insight: Calculate minimum increments needed for each subarray to become non-decreasing, then count those requiring ≤ k operations
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