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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code