DSA problem
Count Partitions With Max-Min Difference at Most K
You are given a 0-indexed integer array nums and an integer k. A subarray of nums is called good if the difference between its maximum and minimum elements is at most k. Return the number of good subarrays of nums.
A direct O(n^2) check considers each subarray and inspects its max and min, but that is too slow for n up to 10^5. Notice that the predicate "max - min <= k" is monotone with respect to enlarging the window: if a window is good, every sub-window inside it is also good. This monotonicity is the green light for a sliding-window approach.
The challenge is efficiently maintaining the running max and min as the window expands and contracts. Two monotonic deques solve this elegantly. The max deque holds indices with values in strictly decreasing order from front to back, so its front is the window maximum. The min deque is the analogous monotonic increasing deque whose front is the window minimum.
For each right endpoint r, expand the window by pushing r into both deques (popping the appropriate back ends to preserve monotonicity). Then, while the window is bad (max - min > k), advance the left pointer and remove deque fronts that have fallen out of the window. The number of good subarrays ending at r is exactly r - l + 1. Summing this across all r gives the answer in O(n) time and O(n) space.
Examples
nums = [1,2,3], k = 15nums = [1,3,1], k = 14nums = [4,5,6,7], k = 29Constraints
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^9
- 0 <= k <= 10^9
- A subarray is good when its max minus its min is at most k.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.