1305. One Fix Calm Stretch

A weather station logs n temperature readings in the array nums. A stretch of consecutive readings is called calm when its largest reading minus its smallest reading is at most limit. Before judging a stretch you may fix at most one reading inside it, replacing that reading with any integer you like. Return the length of the longest stretch that is calm after at most one such fix; a single reading is always calm. A stretch can be fixed exactly when dropping one copy of its maximum or one copy of its minimum leaves a spread of at most limit, and that stays true when the stretch shrinks, so two pointers work with a structure giving the two largest and two smallest values. Target O(n log n) time.

Example 1

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

The stretch [1, 9, 2] becomes calm by replacing 9 with 2 or 1, giving length 3, and no stretch of 4 works.

Example 2

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

All three readings are already equal, so the whole log is calm with length 3.

Example 3

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

In [0, 100, 0] the 100 can be replaced by 0, so a stretch of length 3 is calm, but all four readings cannot be.

Constraints

1 ≤ n ≤ 105

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 10,000 msC++ 2,500 msJava 5,000 msJavaScript 5,000 msTypeScript 5,000 ms

Expected complexity

Time
O(n log 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…