Longest Continuous Subarray With Absolute Diff ≤ Limit
Given an integer array nums and an integer limit, return the size of the longest contiguous subarray such that the absolute difference between any two of its elements is at most limit (equivalently, its max minus its min is at most limit).
Open official problem prompt ↗Find the longest contiguous slice whose largest and smallest elements differ by no more than limit.
Picture a moving thermostat window: you slide a frame over daily temperatures and want the longest stretch where the hottest and coldest days differ by at most limit degrees. You keep two 'leaderboards' — one for the current hottest day, one for the coldest — and whenever the spread between the two leaders grows too big, you trim the oldest days off the back.
- Input
- nums = [8,2,4,7], limit = 4
- Output
- 2
- Why
- [2,4] has max-min = 2 <= 4 and [4,7] has spread 3 <= 4, but every length-3 window (e.g. [2,4,7], spread 5) exceeds the limit, so the longest valid length is 2.
1 <= nums.length <= 10^51 <= nums[i] <= 10^90 <= limit <= 10^9