#3835

Count Subarrays With Cost Less Than or Equal to K

Medium
ArrayQueueMonotonic QueueHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a sliding window and monotonic deques allows us to efficiently track the max and min values in the current subarray, reducing the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize two deques to maintain indices of max and min values.
  2. 2Step 2: Use a sliding window approach to expand the right end until the cost exceeds k.
  3. 3Step 3: Count valid subarrays by adjusting the left end of the window.
solution.py18 lines
1from collections import deque
2
3def countSubarrays(nums, k):
4    n = len(nums)
5    left = 0
6    count = 0
7    max_deque, min_deque = deque(), deque()
8    for right in range(n):
9        while max_deque and nums[max_deque[-1]] <= nums[right]: max_deque.pop()
10        while min_deque and nums[min_deque[-1]] >= nums[right]: min_deque.pop()
11        max_deque.append(right)
12        min_deque.append(right)
13        while (nums[max_deque[0]] - nums[min_deque[0]]) * (right - left + 1) > k:
14            left += 1
15            if max_deque[0] < left: max_deque.popleft()
16            if min_deque[0] < left: min_deque.popleft()
17        count += right - left + 1
18    return count

Complexity note: The sliding window approach processes each element at most twice, leading to O(n) time complexity.

  • 1Using deques allows efficient tracking of max/min values.
  • 2Sliding window helps maintain valid subarray bounds.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.