Longest stretch of readings within a tolerance

Write codeMedium25 minGoogle style

Your task

A factory sensor logs one temperature reading per second. Quality control wants the longest stretch of consecutive readings that stays within a tolerance band.

Write longest_subarray_within_limit(nums, limit) that returns the length of the longest such stretch.

Input and output:

  • nums: a list of 1 to 100,000 integers, each between -2,147,483,648 and 2,147,483,647.
  • limit: an integer between 0 and 4,294,967,295.
  • Returns an integer.

Rules:

  • A stretch is a contiguous, non-empty run of the list.
  • A stretch is within the band when every two readings in it differ by at most limit.
  • A single reading is always within the band, so the answer is at least 1.

Examples

longest_subarray_within_limit(nums: list[int], limit: int) -> int
Example 1
Inputlongest_subarray_within_limit([8, 2, 4, 7], 4)
Output2
Example 2
Inputlongest_subarray_within_limit([1, 5, 6, 7, 8, 10, 6, 5, 6], 4)
Output5