Show problems as
Classic problem #1438MediumArrayQueueSliding WindowHeap (Priority Queue)Ordered SetMonotonic Queue

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

Real-world version: Steady Pressure Span
Tracked in this browser only
Learn the pattern firstSliding Window Maximum/Minimum · Priority Queues, animated step by step

A pipeline crew samples the line pressure once a minute for a whole shift. readings[i] is the gauge value, in kilopascals, taken at minute i, and every gauge value is at least 1.

A run of consecutive minutes counts as steady when the highest and the lowest value recorded anywhere in that run differ by no more than spread. Note that this is judged on the extremes of the whole run, not on how much the gauge moves from one minute to the next.

Return how many minutes long the longest steady run is. A run of one minute has nothing to differ from itself, so the answer is never below 1.

Examples

Example 1

Input
readings = [7, 3, 9, 8, 6], spread = 3
Output
3

Minutes 2 through 4 read 9, 8 and 6, whose extremes differ by exactly 3, so that run of three is steady. No run of four minutes is.

Example 2

Input
readings = [5, 5, 5, 1], spread = 0
Output
3

A spread of 0 admits only runs where every value is identical, and the longest of those is the opening three minutes.

Example 3

Input
readings = [4, 10, 4], spread = 5
Output
1

Both neighbouring pairs differ by 6, so no run of two minutes holds, and the answer falls back to a single minute.

Constraints

  • 1 <= readings.length <= 10^5
  • 1 <= readings[i] <= 10^9
  • 0 <= spread <= 10^9

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def steady_pressure_span(readings: list[int], spread: int) -> int:
Java
public int steadyPressureSpan(int[] readings, int spread)