Continuous Subarrays

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, 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.

Example 1
Inputnums = [5,4,2,4]
Output8
There are 4 continuous subarrays of size 1, 3 of size 2, 1 of size 3, and none of size 4, for a total of 8.
Example 2
Inputnums = [1,2,3]
Output6
All subarrays are continuous, giving 3 subarrays of size 1, 2 of size 2, and 1 of size 3, for a total of 6.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate