-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonotonicQueue.js
More file actions
39 lines (32 loc) · 795 Bytes
/
monotonicQueue.js
File metadata and controls
39 lines (32 loc) · 795 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class MonotonicQueue {
constructor() {
this.queue = [];
}
push(value) {
while (this.queue.length > 0 && this.queue[this.queue.length - 1] < value) {
this.queue.pop();
}
this.queue.push(value);
}
pop(value) {
if (this.queue.length > 0 && this.queue[0] === value) {
this.queue.shift();
}
}
max() {
return this.queue[0];
}
}
function maxSlidingWindow(nums, k) {
let mq = new MonotonicQueue();
let result = [];
for (let i = 0; i < nums.length; i++) {
mq.push(nums[i]);
if (i >= k - 1) {
result.push(mq.max());
mq.pop(nums[i - k + 1]);
}
}
return result;
}
console.log(maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3));