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.
Input Format
- An integer array
nums. - You may assume the array is already provided in memory as a list of integers.
Output Format
- Return a single integer: the number of contiguous subarrays whose maximum and minimum differ by at most 2.
Constraints
- Values may be positive, negative, or zero.
- The intended efficient solution should be near linear time.
- The array can be large enough that an enumeration may be too slow.
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
Unlock deeper context for this problem
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.