Skip to content

Commit 9827f03

Browse files
authored
Update 1425-constrained-subsequence-sum.js
1 parent cb5b1db commit 9827f03

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

1425-constrained-subsequence-sum.js

+77
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,80 @@ const constrainedSubsetSum = function(nums, k) {
2020
}
2121
return max;
2222
};
23+
24+
// another
25+
26+
/**
27+
* @param {number[]} nums
28+
* @param {number} k
29+
* @return {number}
30+
*/
31+
const constrainedSubsetSum = function (nums, k) {
32+
const dll = new DLL()
33+
dll.push([0, nums[0]])
34+
let max = nums[0]
35+
for (let i = 1; i < nums.length; i++) {
36+
// console.log(dll, dll.peek())
37+
let [index, lastKsum] = dll.peek().val
38+
39+
if (index == i - k) {
40+
dll.shift()
41+
}
42+
const sum = Math.max(lastKsum, 0) + nums[i]
43+
max = Math.max(max, sum)
44+
while (!dll.isEmpty() && dll.peekLast().val[1] < sum) {
45+
dll.pop()
46+
}
47+
dll.push([i, sum])
48+
}
49+
return max
50+
}
51+
52+
class Node {
53+
constructor(val) {
54+
this.val = val
55+
this.prev = null
56+
this.next = null
57+
}
58+
}
59+
class DLL {
60+
constructor() {
61+
this.head = new Node()
62+
this.tail = null
63+
}
64+
peek() {
65+
return this.head.next
66+
}
67+
peekLast() {
68+
return this.tail
69+
}
70+
isEmpty() {
71+
return this.head.next == null
72+
}
73+
shift() {
74+
const h = this.head.next
75+
if (h) {
76+
this.head.next = h.next
77+
if (h.next) {
78+
h.next.prev = this.head
79+
} else {
80+
this.tail = null
81+
}
82+
}
83+
}
84+
pop() {
85+
if (this.tail == null) return
86+
const newTail = this.tail.prev
87+
if (newTail) {
88+
newTail.next = null
89+
this.tail.prev = null
90+
this.tail = newTail
91+
}
92+
}
93+
push(val) {
94+
const node = new Node(val)
95+
node.prev = this.tail ?? this.head
96+
node.prev.next = node
97+
this.tail = node
98+
}
99+
}

0 commit comments

Comments
 (0)