Hey everyone, I’m working on a small analytics helper and trying to compute the max for each window without rescanning, but my deque version goes weird when the old max sits near the left edge and I end up trading speed for wrong results.
function maxSlidingWindow(nums, k) {
const dq = [];
const out = [];
for (let i = 0; i < nums.length; i++) {
while (dq.length && nums[dq[dq.length - 1]] <= nums[i]) {
dq.pop();
}
dq.push(i);
if (dq.length && dq[0] <= i - k + 1) {
dq.shift();
}
if (i >= k - 1) {
out.push(nums[dq[0]]);
}
}
return out;
}
console.log(maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3));
What am I getting wrong in the window-expiry check that makes the deque throw away a valid max too soon?
MechaPrime