Problem Description
Given an array nums, count the total number of continuous subarrays for which the absolute difference between any two elements in the subarray is at most 2. A subarray is defined as a contiguous non-empty sequence within the array.
Key Insights
- The condition on the subarray can be rephrased as ensuring that the difference between the maximum and minimum value in the subarray is at most 2.
- A sliding window technique is ideal because subarrays are contiguous.
- Use two monotonic queues (or deques) to efficiently track the minimum and maximum values in the current window.
- When the condition breaks (i.e., max - min > 2), adjust the window by moving the left pointer appropriately.
- The number of subarrays ending at the current right pointer is the window's length (right - left + 1).
Space and Time Complexity
Time Complexity: O(n) because each element is processed at most twice (once when added and once when removed). Space Complexity: O(n) in the worst case for the deques, though typical use is much lower.
Solution
We use a sliding window approach where we maintain two deques: one that keeps track of the maximum values (in decreasing order) and one for the minimum values (in increasing order) within the current window. For each new element at the right pointer, we update both deques. If the difference between the front elements of the maximum and minimum deques exceeds 2, we slide the left pointer until the condition is restored. The count of valid subarrays ending at the current right index is the size of the window, which is then added to the overall answer.