Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Queues
Google
Continuous Subarrays

Count the number of contiguous subarrays where the difference between the maximum and minimum elements is at most 2.

Acceptance 0%
Problem Statement

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

  • 1nums.length1 \le nums.length
  • Values may be positive, negative, or zero.
  • The intended efficient solution should be near linear time.
  • The array can be large enough that an O(n2)O(n^2) enumeration may be too slow.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.