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 <= 105
1 <= nums[i] <= 109
0 <= k <= 1015
Solutions
Solution 1: Deque + Enumeration + Two Pointers
We notice that if a subarray \(\text{nums}[l..r]\) has a cost less than or equal to \(k\), then for any \(l' \geq l\) and \(r' \leq r\), the subarray \(\text{nums}[l'..r']\) also has a cost less than or equal to \(k\). Therefore, we can enumerate the right endpoint \(r\), use two pointers to maintain the minimum left endpoint \(l\) that satisfies the condition, then the number of subarrays ending at \(r\) that satisfy the condition is \(r - l + 1\), which we accumulate to the answer.
We can use two deques to maintain the maximum and minimum values in the current window respectively.
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\text{nums}\).