You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:

Let i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, we have 0 <= |nums[i1] - nums[i2]| <= 2.

Return the total number of continuous subarrays.

A subarray is a contiguous non-empty sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,4,2,4]
Output: 10
💡 Note: All valid subarrays: [5], [4], [2], [4], [5,4], [4,2], [2,4], [4,2,4], [5,4,2] (invalid: |5-2|=3>2), so 10 total
Example 2 — Small Array
$ Input: nums = [1,2,3]
Output: 6
💡 Note: All subarrays are continuous: [1], [2], [3], [1,2], [2,3], [1,2,3] → 6 total
Example 3 — Large Differences
$ Input: nums = [1,10,2]
Output: 4
💡 Note: Valid subarrays: [1], [10], [2], [2,10] (invalid: [1,10] since |1-10|=9>2) → 4 total

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Continuous Subarrays: Count Valid SubarraysA subarray is continuous if max - min ≤ 25424✓ Valid subarrays (10 total):Single: [5], [4], [2], [4]Pairs: [5,4], [4,2], [2,4]Triple: [4,2,4]Quad: none (max-min > 2)[5,4,2]: 5-2=3>2 ✗Result: 10
Understanding the Visualization
1
Input
Array [5,4,2,4] - find continuous subarrays
2
Process
Check each subarray: max - min ≤ 2
3
Output
Count: 10 valid continuous subarrays
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently maintain subarrays where max-min ≤ 2
Asked in
Google 25 Amazon 18 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen