Problem 341466 · hard · Phase 03 Linear Management & Searching

Longest Tight Band

sliding window · monotonic deque · variable-size window

A pressure gauge logs readings in readings. A stretch of consecutive readings is tight if the difference between its largest and smallest reading is at most limit. Return the length of the longest tight stretch.

Examples

Input:  readings = [8, 2, 4, 7], limit = 4
Output: 2
Explanation: [2, 4] and [4, 7] are tight; no stretch of length 3 is.

Input:  readings = [10, 1, 2, 4, 7, 2], limit = 5
Output: 4
Explanation: [2, 4, 7, 2] has max 7 and min 2.

Input:  readings = [4, 2, 2, 2, 4, 4, 2, 2], limit = 0
Output: 3

Constraints

  • 1 <= len(readings) <= 10**5
  • -10**9 <= readings[i] <= 10**9, 0 <= limit <= 10**9
  • Target complexity: O(n) time. Recomputing max and min for each candidate window is too slow for the largest tests.

Goals

  • Maintain both the window maximum and minimum with two monotonic deques
  • Shrink the window from the left while keeping the deques consistent
Starting Python…