The example with [2,4,6] and k=2 gives 2, which checks out (subarrays [2,4] and [4,6]).
Clarify the problem and constraints, then propose an efficient algorithm using two monotonic deques to maintain the sliding window's max and min. Explain how to count subarrays with difference exactly K by computing counts for difference ≤ K and subtracting counts for difference ≤ K-1.
Pro tip: Mention that the two-pointer sliding window works because the max-min difference is monotonic with respect to window expansion, and explicitly state the time and space complexity (O(n) time, O(n) space) to demonstrate optimization awareness.
Ask about array size, possible negative values, and whether the difference can be zero. Confirm that subarrays are contiguous and that we need to count all such subarrays.
Design a function that counts subarrays where max-min ≤ K using a sliding window with two deques to track max and min in O(n) time.
Compute count(≤ K) - count(≤ K-1) to obtain the number of subarrays with max-min exactly equal to K.
Maintain two deques: one decreasing for max, one increasing for min. Expand right pointer, adjust left pointer when difference exceeds K, and add (right - left + 1) to the count.
State O(n) time and O(n) space. Test with small arrays, all equal elements, K=0, and large K to ensure correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.