Count Non-Decreasing Subarrays After K Operations Problem
Description
LeetCode Problem 3420.
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 <= 10^51 <= nums[i] <= 10^91 <= k <= 10^9
Solution
Approach: Two Pointers + Monotonic Queue
An operation raises an element by 1. To make a subarray non-decreasing at the lowest cost, raise every element up to the maximum seen so far (the prefix maximum). So the cost of a subarray is the sum of prefixMax - element.
Fix the left end l and call the farthest valid right end r. A subarray that is valid for l is also valid for l + 1 (it has the same elements minus one), so as l moves left, r can only move left too. We sweep l from the end of the array towards the start with r following it. We keep the current window [l, r] and its cost in a monotonic queue of indexes of non-increasing values, which are exactly the places where the prefix maximum changes.
- Adding
nums[l]on the left may exceed the values at the back of the queue. Pop each of them and increase the cost by the amount their stretch of positions now has to be raised. - While the cost exceeds
k, shrink the window from the right: removenums[r], subtract the amount the front of the queue contributed for it, and pop the front when it isr. - Every
r' <= ris valid for thisl, so addr - l + 1to the answer.
Complexity: O(n) time and O(n) space, since each index enters and leaves the queue once.
from collections import deque
class Solution:
def countNonDecreasingSubarrays(self, nums: List[int], k: int) -> int:
n = len(nums)
q = deque()
ans = 0
cost = 0
r = n - 1
for l in range(n - 1, -1, -1):
x = nums[l]
while q and nums[q[-1]] <= x:
s = q.pop()
end = q[-1] if q else r + 1
cost += (end - s) * (x - nums[s])
q.append(l)
while cost > k:
cost -= nums[q[0]] - nums[r]
if q[0] == r:
q.popleft()
r -= 1
ans += r - l + 1
return ans