176. Calm Stretch

A weather station stores one pressure reading per hour in the array nums. A stretch of consecutive hours is called calm if the difference between its highest and lowest reading is at most limit.

Return the length of the longest calm stretch. A single reading is always a calm stretch of length 1, because its highest and lowest readings are the same value. Readings may differ by more than a 32-bit integer can hold when compared across the whole input, so compute differences with care.

Example 1

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

The stretch [2,4] has range 2 and [4,7] has range 3, both within 4. Adding a third reading to either makes the range 5 or more, so the longest calm stretch has length 2.

Example 2

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

The stretch [2,4,7,2] has highest 7 and lowest 2, a range of 5, which is allowed. No stretch of length 5 stays within 5, so the answer is 4.

Example 3

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

With limit 0 all readings in a stretch must be equal. The longest such stretch is [2,2,2] of length 3.

Constraints

1 ≤ nums.length ≤ 105

-109 ≤ 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…