Skip to main content

Count Subarrays With Cost Less Than or Equal to K - Solution & Explanation

Practice this problem

Problem Statement

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 <= 105
  • 1 <= nums[i] <= 109
  • 0 <= k <= 1015

Approach Overview

Problem 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 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.

Solution

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.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force EnumerationO(n²)O(1)Useful for understanding the problem or validating small test cases
Sliding Window with Recalculated MaxO(n²) worst caseO(1)When constraints are moderate and recomputing the max is acceptable
Monotonic Deque + Two PointersO(n)O(n)Optimal solution for large arrays when the cost depends on the window maximum

Video Solution

Count Subarrays With Cost Constraint | LeetCode 3835 | Sliding Window & MultisetSanyam IIT Guwahati1,718 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Subarrays With Cost Less Than or Equal to K easy or hard?
The problem is typically classified as Medium difficulty. The main challenge is recognizing that the cost depends on a window extreme and that a monotonic deque can maintain that value efficiently while using a sliding window.
Count Subarrays With Cost Less Than or Equal to K Python/Java solution
Implement the sliding window and maintain a deque for the window maximum. Track the running sum and adjust the left pointer whenever the computed cost becomes greater than k. The same logic works across Python, Java, C++, Go, and TypeScript with O(n) time complexity.
How to solve Count Subarrays With Cost Less Than or Equal to K in O(n)?
Use a two-pointer sliding window and maintain the maximum element with a monotonic deque. As the right pointer expands the window, update the running sum and deque. If the cost exceeds k, move the left pointer forward until the window becomes valid again. For each right index, add the number of valid subarrays ending at that index.
What is the best approach for Count Subarrays With Cost Less Than or Equal to K?
The most efficient solution uses a sliding window with a monotonic deque. The deque keeps track of the maximum element in the current window while two pointers expand and shrink the window. This allows the cost of each subarray to be computed in constant time, resulting in an overall O(n) time complexity.
Is Count Subarrays With Cost Less Than or Equal to K asked at Google/Amazon/Meta?
Problems involving sliding windows and monotonic queues frequently appear in interviews at companies like Amazon, Google, and Meta. Variations that require maintaining a window maximum while counting valid subarrays are particularly common in medium-level interview rounds.
What data structure is used in Count Subarrays With Cost Less Than or Equal to K?
The key data structure is a monotonic deque (monotonic queue). It stores indices in decreasing order of values so the maximum element of the current window is always at the front. This structure enables constant-time maximum queries during sliding window updates.
What is the time complexity of Count Subarrays With Cost Less Than or Equal to K?
The optimal algorithm runs in O(n) time because each element enters and leaves the sliding window at most once. Maintaining the maximum value with a monotonic deque ensures constant amortized time updates. The space complexity is O(n) for the deque structure.

Ready to solve this problem?

Practice Count Subarrays With Cost Less Than or Equal to K with our built-in code editor and test cases.

Practice on FleetCode