↓Skip to main content
  1. LeetCode/

LeetCode 3835: Count Subarrays With Cost Less Than or Equal to K

·2 mins· ·
LeetCode Medium Sliding-Window Monotonic-Queue Queue Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-02-08

  • Submissions: Wrong Answer → Accepted

Approach
#

cost = (max - min) × length. As the window grows, max - min never shrinks and the length grows, so cost only increases, which makes the condition monotonic:

  • Add on the right; shrink the left while the cost is > k.
  • There are right - left + 1 valid subarrays ending at right.

The window’s max and min come from two monotonic deques of indices:

  • The max deque has decreasing values: before adding, pop back entries <= the new value.
  • The min deque has increasing values: pop back entries >= it.
  • After the left boundary moves, pop front indices < left (expired).

My Attempts
#

Attempt 1 used lists as queues and mixed the “expired” check into the loop that pops from the back (max_stack[0] < left), with the min side written as min_stack[0] > left. Expired entries belong at the front, which is a separate job from popping dominated entries at the back. For nums = [6, 2, 3], k = 9, the answer is 5; it returned 6.

Two deques, with the back handling only dominated entries and the front handling only expired ones, passed.

Solution
#

from collections import deque

class Solution:
    def countSubarrays(self, nums: List[int], k: int) -> int:
        max_q, min_q = deque(), deque()            # indices
        left = count = 0
        for right, x in enumerate(nums):
            while max_q and nums[max_q[-1]] <= x:
                max_q.pop()
            max_q.append(right)
            while min_q and nums[min_q[-1]] >= x:
                min_q.pop()
            min_q.append(right)

            while (nums[max_q[0]] - nums[min_q[0]]) * (right - left + 1) > k:
                left += 1
                if max_q[0] < left:
                    max_q.popleft()                # expired
                if min_q[0] < left:
                    min_q.popleft()
            count += right - left + 1
        return count

With left == right the cost is 0 and k >= 0, so the shrinking loop never empties the deques.

Complexity
#

Time O(n): each index enters and leaves each deque once. Space O(n).

Mistakes to Avoid
#

  • Mixing “expired” and “dominated” into one condition: one pops from the front, the other from the back.
  • Using list.pop(0) as a queue: O(n) each time.

Interview Explanation
#

Cost is max minus min times length, and it only grows with the window, so a sliding window works: shrink the left while the cost exceeds k, and right - left + 1 valid subarrays end at the right boundary. Two monotonic deques give the window’s max and min, popping dominated entries at the back and expired ones at the front. Each index enters and leaves once, so time is O(n).

Related

LeetCode 2537: Count the Number of Good Subarrays
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 2537 note: adding x creates cnt[x] new equal pairs and removing it loses cnt[x] - 1; an “at least k pairs” counting window with count += left
LeetCode 2875: Minimum Size Subarray in Infinite Array
·2 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 2875 note: strip target // sum full cycles; the remainder is smaller than one cycle, so a sliding window over two copies of nums always finds it
LeetCode 3413: Maximum Coins From K Consecutive Bags
·3 mins
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 3413 note: the best k bags always have one end on a segment boundary; compute “left end at a segment start” and “right end at a segment end” (the latter by mirroring and reusing the same function)
LeetCode 2779: Maximum Beauty of an Array After Applying Operation
·2 mins
LeetCode Medium Sliding-Window Sorting Binary-Search Array
LeetCode 2779 note: each number can become anything in [x - k, x + k], so a group can become one value ⇔ max - min <= 2k; sort and find the longest such window
LeetCode 2831: Find the Longest Equal Subarray
·2 mins
LeetCode Medium Sliding-Window Hash-Table Binary-Search Array
LeetCode 2831 note: list the positions of each value and slide a window over that list; the deletions needed are the span of positions minus the number of copies
LeetCode 3795: Minimum Subarray Length With Distinct Sum At Least K
·2 mins
LeetCode Medium Sliding-Window Hash-Table Array
LeetCode 3795 note: a shortest-window slide where each value counts once; track each value’s last position, and subtract the left value only if it was the last occurrence