1281. Narrow Band Stretches

A weather station records one temperature reading per hour and stores the readings in the array nums. A run of consecutive hours is called steady when the difference between the largest and the smallest reading inside it is at most limit. Count the steady runs. Every non-empty contiguous subarray of nums is judged on its own and identified by its position, so two runs with equal values at different positions are counted separately.

Return the count as a 64-bit integer, because it can be far larger than a 32-bit value. The array can hold up to 200000 readings, so aim for O(n) time and O(n) extra space, for example two pointers combined with a pair of monotonic deques.

Example 1

Input:
nums = [3,1,4,1,5], limit = 2
Output:
6
Explanation:

The five single elements and the pair (3, 1) have a spread of at most 2, and no longer stretch does, so the count is 6.

Example 2

Input:
nums = [7,7,7], limit = 0
Output:
6
Explanation:

All values are equal, so every one of the 3 + 2 + 1 = 6 subarrays has spread 0.

Example 3

Input:
nums = [1,2,3,4], limit = 1
Output:
7
Explanation:

The 4 single elements and the 3 adjacent pairs qualify; every longer stretch has spread 2 or more, giving 7.

Constraints

  • 1 ≤ n ≤ 2 * 105, where n is the length of nums
  • 0 ≤ nums[i] ≤ 109
  • 0 ≤ limit ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…