๐ฏ Count Continuous Subarrays
You're given a 0-indexed integer array nums. Your task is to find the total number of continuous subarrays.
A subarray is called continuous if for any two elements in the subarray, their absolute difference is at most 2. In other words, if we have indices i, i+1, ..., j in the subarray, then for every pair of indices i1, i2 where i โค i1, i2 โค j, we need |nums[i1] - nums[i2]| โค 2.
Example: In array [5, 4, 2, 4], the subarray [5, 4] is continuous because |5-4| = 1 โค 2, but [5, 4, 2] is not continuous because |5-2| = 3 > 2.
Return the total count of all such continuous subarrays.
Input & Output
Visualization
Time & Space Complexity
Each element is added and removed from deques at most once, and each element is processed once
In worst case, deques can store up to O(n) elements
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- Important: The absolute difference condition must hold for ALL pairs in the subarray, not just adjacent elements