Show problems as
Classic problem #2762MediumArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue

Continuous Subarrays

Real-world version: Stretches Whose Readings Stay Within Two
Tracked in this browser only
Read Continuous Subarrays on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A log holds the readings readings. A stretch of neighbouring readings is steady when its largest reading and its smallest differ by at most 2. A stretch of one reading is always steady.

Return how many steady stretches the log holds.

Examples

Example 1

Input
readings = [1, 3, 5]
Output
5

The three single readings are steady, and so are the two neighbouring pairs, each spread exactly two. The whole log spreads four, so it is not.

Example 2

Input
readings = [7, 7, 7]
Output
6

Every reading is the same, so every stretch has no spread at all and all six count.

Example 3

Input
readings = [1, 10]
Output
2

The two readings spread nine, so only the two single readings are steady.

Constraints

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

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def continuous_subarrays(readings: list[int]) -> int:
Java
public long continuousSubarrays(int[] readings)