Skip to content

Commit 0d1d9e4

Browse files
authored
Update 502-ipo.js
1 parent 4aeb04a commit 0d1d9e4

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

502-ipo.js

+95
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,98 @@
1+
/**
2+
* @param {number} k
3+
* @param {number} W
4+
* @param {number[]} Profits
5+
* @param {number[]} Capital
6+
* @return {number}
7+
*/
8+
const findMaximizedCapital = function(k, W, Profits, Capital) {
9+
const capPQ = new PriorityQueue((a, b) => a.cap < b.cap)
10+
const proPQ = new PriorityQueue((a, b) => a.pro > b.pro)
11+
for(let i = 0, len = Profits.length; i < len; i++) {
12+
capPQ.push({ cap: Capital[i], pro: Profits[i] })
13+
}
14+
while(k) {
15+
while(!capPQ.isEmpty() && capPQ.peek().cap <= W) {
16+
proPQ.push(capPQ.pop())
17+
}
18+
if(proPQ.isEmpty()) break
19+
20+
W += proPQ.pop().pro
21+
k--
22+
}
23+
return W
24+
};
25+
26+
class PriorityQueue {
27+
constructor(comparator = (a, b) => a > b) {
28+
this.heap = []
29+
this.top = 0
30+
this.comparator = comparator
31+
}
32+
size() {
33+
return this.heap.length
34+
}
35+
isEmpty() {
36+
return this.size() === 0
37+
}
38+
peek() {
39+
return this.heap[this.top]
40+
}
41+
push(...values) {
42+
values.forEach((value) => {
43+
this.heap.push(value)
44+
this.siftUp()
45+
})
46+
return this.size()
47+
}
48+
pop() {
49+
const poppedValue = this.peek()
50+
const bottom = this.size() - 1
51+
if (bottom > this.top) {
52+
this.swap(this.top, bottom)
53+
}
54+
this.heap.pop()
55+
this.siftDown()
56+
return poppedValue
57+
}
58+
replace(value) {
59+
const replacedValue = this.peek()
60+
this.heap[this.top] = value
61+
this.siftDown()
62+
return replacedValue
63+
}
64+
65+
parent = (i) => ((i + 1) >>> 1) - 1
66+
left = (i) => (i << 1) + 1
67+
right = (i) => (i + 1) << 1
68+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
69+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
70+
siftUp = () => {
71+
let node = this.size() - 1
72+
while (node > this.top && this.greater(node, this.parent(node))) {
73+
this.swap(node, this.parent(node))
74+
node = this.parent(node)
75+
}
76+
}
77+
siftDown = () => {
78+
let node = this.top
79+
while (
80+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
81+
(this.right(node) < this.size() && this.greater(this.right(node), node))
82+
) {
83+
let maxChild =
84+
this.right(node) < this.size() &&
85+
this.greater(this.right(node), this.left(node))
86+
? this.right(node)
87+
: this.left(node)
88+
this.swap(node, maxChild)
89+
node = maxChild
90+
}
91+
}
92+
}
93+
94+
// another
95+
196
/**
297
* @param {number} k
398
* @param {number} W

0 commit comments

Comments
 (0)