Count the number of contiguous subarrays where the difference between the maximum and minimum elements is at most 2.
Given an integer array, count how many contiguous subarrays are continuous: for every valid subarray, the difference between its maximum value and minimum value is at most 2.
Your task is to return the total number of contiguous subarrays that satisfy this condition.
A subarray is a contiguous, non-empty slice of the array.
nums.Example 1
Input
nums = [5,4,2,4]
Output
8
Explanation
Valid continuous subarrays are: [5], [4], [2], [4], [5,4], [4,2], [2,4], [5,4,2]. The subarray [4,2,4] is invalid because max - min = 2, actually it is valid; and [5,4,2,4] is invalid because 5 - 2 = 3. Counting all valid subarrays gives 8.
Example 2
Input
nums = [1,2,3]
Output
6
Explanation
Every subarray is valid because the maximum difference in any subarray is at most 2.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.