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 = 0nums[0..1]: cost = (3 - 1) * 2 = 4nums[0..2]: cost = (3 - 1) * 3 = 6nums[1..1]: cost = (3 - 3) * 1 = 0nums[1..2]: cost = (3 - 2) * 2 = 2nums[2..2]: cost = (2 - 2) * 1 = 0There 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 <= 1051 <= nums[i] <= 1090 <= k <= 1015Problem Overview: Given an integer array, count how many subarrays have a computed cost less than or equal to k. The cost depends on values inside the subarray, so the goal is to efficiently expand and shrink windows while tracking the elements that determine that cost.
Approach 1: Brute Force Enumeration (O(n²) time, O(1) space)
Start every subarray from index i and extend it one element at a time to the right. Recompute the cost for each candidate subarray and check whether it is ≤ k. Every valid window increments the answer. This approach is straightforward and useful for verifying logic on small inputs, but it becomes slow for large arrays because it evaluates roughly n² subarrays. No additional data structures are required beyond a few variables.
Approach 2: Sliding Window with Running Statistics (O(n)–O(n log n) time, O(1) space)
Instead of recomputing everything for each subarray, maintain a sliding window using the two pointers technique. The right pointer expands the window while the left pointer shrinks it when the cost exceeds k. Maintaining values like a running sum reduces repeated computation. However, if the cost depends on the maximum element inside the window, updating that value efficiently becomes difficult without additional structure. In the worst case you may still spend extra time recalculating the max element.
Approach 3: Monotonic Deque + Two Pointers (O(n) time, O(n) space)
The optimal solution combines a sliding window with a monotonic queue. As the right pointer moves, push indices into a deque while maintaining decreasing order of values. The front of the deque always stores the maximum element of the current window. At the same time maintain a running sum of the window elements. Using these values you can compute the subarray cost in constant time. If the cost exceeds k, move the left pointer forward, update the sum, and remove indices that fall out of the window from the deque.
Every time the window becomes valid, all subarrays ending at the current right index are valid. Add right - left + 1 to the result. Each element enters and leaves the deque at most once, so the entire algorithm runs in linear time. This technique relies on efficient max retrieval from a deque and is common in problems involving window extremes on an array.
Recommended for interviews: Interviewers expect the sliding window combined with a monotonic deque. Showing the brute force approach first demonstrates problem understanding, but the deque-based solution proves you know how to maintain window maximums in O(1) amortized time and achieve O(n) complexity.
We notice that if a subarray nums[l..r] has a cost less than or equal to k, then for any l' geq l and r' leq r, the subarray 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 nums.
Python
Java
C++
Go
TypeScript
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Enumeration | O(n²) | O(1) | Useful for understanding the problem or validating small test cases |
| Sliding Window with Recalculated Max | O(n²) worst case | O(1) | When constraints are moderate and recomputing the max is acceptable |
| Monotonic Deque + Two Pointers | O(n) | O(n) | Optimal solution for large arrays when the cost depends on the window maximum |
Count Subarrays With Cost Constraint | LeetCode 3835 | Sliding Window & Multiset • Sanyam IIT Guwahati • 1,630 views views
Watch 9 more video solutions →Practice Count Subarrays With Cost Less Than or Equal to K with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor