Count Subarrays With Cost Less Than or Equal to K Problem
Description
LeetCode Problem 3835.
You are given an integer array nums, and an integer k.
For any subarray nums[l..r], define its cost as:
cost = (max(nums[l..r]) - min(nums[l..r])) * (r - l + 1).
Return an integer denoting the number of subarrays of nums whose cost is less than or equal to k.
Example 1:
Input: nums = [1,3,2], k = 4
Output: 5
Explanation:
We consider all subarrays of nums:
- nums[0..0]: cost = (1 - 1) * 1 = 0
- nums[0..1]: cost = (3 - 1) * 2 = 4
- nums[0..2]: cost = (3 - 1) * 3 = 6
- nums[1..1]: cost = (3 - 3) * 1 = 0
- nums[1..2]: cost = (3 - 2) * 2 = 2
- nums[2..2]: cost = (2 - 2) * 1 = 0
There are 5 subarrays whose cost is less than or equal to 4.
Example 2:
Input: nums = [5,5,5,5], k = 0
Output: 10
Explanation:
For any subarray of nums, the maximum and minimum values are the same, so the cost is always 0.
As a result, every subarray of nums has cost less than or equal to 0.
For an array of length 4, the total number of subarrays is (4 * 5) / 2 = 10.
Example 3:
Input: nums = [1,2,3], k = 0
Output: 3
Explanation:
The only subarrays of nums with cost 0 are the single-element subarrays, and there are 3 of them.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^90 <= k <= 10^15
Solution
Approach: Monotonic Deques + Two Pointers
If a subarray nums[l..r] has cost at most k, every subarray inside it has cost at most k too: its max-minus-min is not larger and it is not longer. So for each right end r there is a smallest left end l such that nums[l..r] is valid, and l never moves left as r grows. Every start in [l, r] gives a valid subarray ending at r, so we add r - l + 1 to the answer.
To read the maximum and minimum of the window quickly, keep two monotonic deques of indices: one with decreasing values (its front is the maximum) and one with increasing values (its front is the minimum). After adding r, move l right while (max - min) * (r - l + 1) > k, dropping deque fronts whose index is now left of l. A single element always has cost 0, so the window never becomes empty.
The cost can reach about 10^14, so use 64-bit integers.
Complexity:
- Time:
O(n), since every index enters and leaves each deque once. - Space:
O(n).
from collections import deque
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ans = 0
q1 = deque()
q2 = deque()
l = 0
for r, x in enumerate(nums):
while q1 and nums[q1[-1]] <= x:
q1.pop()
while q2 and nums[q2[-1]] >= x:
q2.pop()
q1.append(r)
q2.append(r)
while l < r and (nums[q1[0]] - nums[q2[0]]) * (r - l + 1) > k:
l += 1
if q1[0] < l:
q1.popleft()
if q2[0] < l:
q2.popleft()
ans += r - l + 1
return ans