Skip to content

Commit d672b2c

Browse files
authored
Create 0502-ipo.js
1 parent db64a15 commit d672b2c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Diff for: javascript/0502-ipo.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* MaxPriorityQueue | Sorting
3+
* Time O(n*log(n)) | Space O(n)
4+
* https://leetcode.com/problems/ipo/description/
5+
* @param {number} k
6+
* @param {number} w
7+
* @param {number[]} profits
8+
* @param {number[]} capital
9+
* @return {number}
10+
*/
11+
var findMaximizedCapital = function(k, w, profits, capital) {
12+
13+
const maxQueue = new MaxPriorityQueue({
14+
compare: (a,b) => {
15+
return b[0] - a[0];
16+
}
17+
});
18+
19+
const minQueue = new MinPriorityQueue({
20+
compare: (a,b) => {
21+
return a[0] - b[0];
22+
}
23+
});
24+
25+
const pc = profits.map((profit, idx) => {
26+
return [profit, capital[idx]];
27+
});
28+
29+
for(let i = 0; i < pc.length; i++) {
30+
minQueue.enqueue( [pc[i][1], pc[i][0]] );
31+
}
32+
33+
let cc = w;
34+
while(k && (!maxQueue.isEmpty() || !minQueue.isEmpty()) ) {
35+
36+
// add all the project that we can take to maxQ
37+
while(!minQueue.isEmpty() && cc >= minQueue.front()[0]) {
38+
const curr = minQueue.dequeue();
39+
maxQueue.enqueue([curr[1], curr[0]]);
40+
}
41+
42+
if(!maxQueue.isEmpty()) {
43+
cc += maxQueue.dequeue()[0];
44+
}
45+
46+
k--;
47+
}
48+
49+
return cc;
50+
};
51+

0 commit comments

Comments
 (0)