iq.lab
Python starts when a code cell comes near or you run one
mediumQueues and dequesSliding window target 25 min

Longest run within a limit

You get a list of integers nums and a whole number limit. Return the length of the longest run of neighboring items (a stretch of the list with no gaps, also called a subarray) in which every two items differ by at most limit.

Two items differ by the larger one minus the smaller one, so their order does not matter. A single item is a run that always fits, so the answer is at least 1.

Example 1
Inputnums = [3, 7, 4, 6, 1, 2], limit = 3Output3

The run [7, 4, 6] fits: its largest and smallest, 7 and 4, differ by 3. Adding the 3 before it or the 1 after it breaks the limit, and no other run of three fits.

Example 2
Inputnums = [5, 5, 5, 5], limit = 0Output4

Equal items differ by 0, so the whole list fits even with a limit of 0.

Example 3
Inputnums = [1, 4, 8, 13], limit = 2Output1

Every two neighbors differ by more than 2, so the longest runs are single items.

Constraints
  • 1 ≤ len(nums) ≤ 105

  • 1 ≤ nums[i] ≤ 109

  • 0 ≤ limit ≤ 109

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.