| 9 | * @return {number} |
| 10 | */ |
| 11 | var findMaximizedCapital = function (k, w, profits, capital) { |
| 12 | const maxQueue = new MaxPriorityQueue({ |
| 13 | compare: (a, b) => { |
| 14 | return b[0] - a[0]; |
| 15 | }, |
| 16 | }); |
| 17 | |
| 18 | const minQueue = new MinPriorityQueue({ |
| 19 | compare: (a, b) => { |
| 20 | return a[0] - b[0]; |
| 21 | }, |
| 22 | }); |
| 23 | |
| 24 | const pc = profits.map((profit, idx) => { |
| 25 | return [profit, capital[idx]]; |
| 26 | }); |
| 27 | |
| 28 | for (let i = 0; i < pc.length; i++) { |
| 29 | minQueue.enqueue([pc[i][1], pc[i][0]]); |
| 30 | } |
| 31 | |
| 32 | let cc = w; |
| 33 | while (k && (!maxQueue.isEmpty() || !minQueue.isEmpty())) { |
| 34 | // add all the project that we can take to maxQ |
| 35 | while (!minQueue.isEmpty() && cc >= minQueue.front()[0]) { |
| 36 | const curr = minQueue.dequeue(); |
| 37 | maxQueue.enqueue([curr[1], curr[0]]); |
| 38 | } |
| 39 | |
| 40 | if (!maxQueue.isEmpty()) { |
| 41 | cc += maxQueue.dequeue()[0]; |
| 42 | } |
| 43 | |
| 44 | k--; |
| 45 | } |
| 46 | |
| 47 | return cc; |
| 48 | }; |