All problems

Calm Sensor Stretch

Medium · sliding window

A sensor in a greenhouse writes down one reading every minute. You are given the readings in time order as a list readings, and a whole number limit.

A stretch is a run of readings that follow each other with none skipped. A stretch is calm if its highest reading and its lowest reading differ by at most limit. A stretch of a single reading is always calm.

Return the number of readings in the longest calm stretch.

Examples

Example 1

Input: readings = [5, 1, 3, 4, 2, 9, 8], limit = 3

Output: 4

The stretch 1, 3, 4, 2 has a highest reading of 4 and a lowest of 1, a difference of 3. Adding the 5 in front or the 9 behind would break the limit.

Example 2

Input: readings = [7, 7, 7], limit = 0

Output: 3

All three readings are equal, so the whole list is calm even with no room to differ.

Example 3

Input: readings = [1, 10, 20], limit = 5

Output: 1

Every pair of neighbours differs by more than 5, so the best stretch is a single reading.

Constraints