← TopicsSliding Window · 1/18

Longest Subarray with Bounded Range (max - min <= limit)

Given an integer array `nums` and an integer `limit`, return the length of the longest contiguous subarray such that the absolute difference between the maximum and minimum element of the subarray is at most `limit` (i.e. `max - min <= limit`). Use a sliding window with two monotonic deques (one tracking the window maximum, one tracking the window minimum) so the window's range is known in O(1) and each index enters/leaves a deque at most once, giving overall O(n). Batch IO: the first line is T, the number of cases. Each of the next T lines is one case encoded as: `n limit a_0 a_1 ... a_{n-1}` — the array size `n`, the integer `limit`, then `n` integers. For each case print one line: the length of the longest qualifying subarray.

func longestSubarray(nums []int, limit int) int {
var maxDq, minDq []int
left := 0
best := 0
for right := 0; right < len(nums); right++ {
for len(maxDq) > 0 && nums[maxDq[len(maxDq)-1]] <= nums[right] {
maxDq = maxDq[:len(maxDq)-1]
}
maxDq = append(maxDq, right)
minDq = minDq[:len(minDq)-1]
}
minDq = append(minDq, right)
if maxDq[0] == left {
maxDq = maxDq[1:]
}
if minDq[0] == left {
minDq = minDq[1:]
}
left++
}
if right-left+1 > best {
best = right - left + 1
}
}
return best
}

this session — 0 attempt(s), 0 passed, 0 failed. (ephemeral; discarded when you leave)