Problem 341466 · hard · Level 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 = [5, 9, 6, 2, 3, 3], limit = 3
Output: 3
Explanation: [2, 3, 3] has max 3 and min 2; [9, 6] is tight too but shorter.

Input:  readings = [1, 6, 3, 8, 7, 4], limit = 4
Output: 3
Explanation: [8, 7, 4] has max 8 and min 4, a difference of exactly 4.

Input:  readings = [7, 7, 2, 7, 7, 7, 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…