Longest stretch of readings within a tolerance
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) -> intExample 1
Input
longest_subarray_within_limit([8, 2, 4, 7], 4)Output
2Example 2
Input
longest_subarray_within_limit([1, 5, 6, 7, 8, 10, 6, 5, 6], 4)Output
5