Skip to content

Commit db31e08

Browse files
authored
Update 1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js
1 parent dccdcd5 commit db31e08

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,78 @@ const longestSubarray = function(nums, limit) {
2323
}
2424
return j - i;
2525
};
26+
27+
// another
28+
29+
/**
30+
* @param {number[]} nums
31+
* @param {number} limit
32+
* @return {number}
33+
*/
34+
const longestSubarray = function (nums, limit) {
35+
const maxDq = new Deque(), minDq = new Deque(), n = nums.length
36+
let l = 0, r = 0
37+
let res = 0
38+
for(r = 0; r < n; r++) {
39+
const cur = nums[r]
40+
while(!maxDq.isEmpty() && maxDq.last() < cur) {
41+
maxDq.pop()
42+
}
43+
maxDq.enqueue(cur)
44+
while(!minDq.isEmpty() && minDq.last() > cur) {
45+
minDq.pop()
46+
}
47+
minDq.enqueue(cur)
48+
49+
while(maxDq.first() - minDq.first() > limit) {
50+
if(nums[l] === maxDq.first()) maxDq.dequeue()
51+
if(nums[l] === minDq.first()) minDq.dequeue()
52+
l++
53+
}
54+
res = Math.max(res, r - l + 1)
55+
}
56+
return res
57+
}
58+
59+
class Deque {
60+
constructor() {
61+
this.head = new Node()
62+
this.tail = this.head
63+
}
64+
65+
isEmpty() {
66+
return this.head.next === null
67+
}
68+
69+
first() {
70+
return this.head.next.value
71+
}
72+
73+
last() {
74+
return this.tail.value
75+
}
76+
77+
dequeue() {
78+
this.head = this.head.next
79+
this.head.prev = null
80+
}
81+
82+
enqueue(value) {
83+
this.tail.next = new Node(value)
84+
this.tail.next.prev = this.tail
85+
this.tail = this.tail.next
86+
}
87+
88+
pop() {
89+
this.tail = this.tail.prev
90+
this.tail.next = null
91+
}
92+
}
93+
94+
class Node {
95+
constructor(value) {
96+
this.value = value
97+
this.next = null
98+
this.prev = null
99+
}
100+
}

0 commit comments

Comments
 (0)