|
| 1 | +/** |
| 2 | + * 502. IPO |
| 3 | + * https://leetcode.com/problems/ipo/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Suppose LeetCode will start its IPO soon. In order to sell a good price of |
| 7 | + * its shares to Venture Capital, LeetCode would like to work on some projects |
| 8 | + * to increase its capital before the IPO. Since it has limited resources, it |
| 9 | + * can only finish at most k distinct projects before the IPO. Help LeetCode |
| 10 | + * design the best way to maximize its total capital after finishing at most |
| 11 | + * k distinct projects. |
| 12 | + * |
| 13 | + * You are given n projects where the ith project has a pure profit profits[i] |
| 14 | + * and a minimum capital of capital[i] is needed to start it. |
| 15 | + * |
| 16 | + * Initially, you have w capital. When you finish a project, you will obtain |
| 17 | + * its pure profit and the profit will be added to your total capital. |
| 18 | + * |
| 19 | + * Pick a list of at most k distinct projects from given projects to maximize |
| 20 | + * your final capital, and return the final maximized capital. |
| 21 | + * |
| 22 | + * The answer is guaranteed to fit in a 32-bit signed integer. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} k |
| 27 | + * @param {number} w |
| 28 | + * @param {number[]} profits |
| 29 | + * @param {number[]} capital |
| 30 | + * @return {number} |
| 31 | + */ |
| 32 | +var findMaximizedCapital = function(k, w, profits, capital) { |
| 33 | + const queue = new MinPriorityQueue(); |
| 34 | + const descendingQueue = new MaxPriorityQueue(); |
| 35 | + |
| 36 | + for (let i = 0; i < capital.length; i++) { |
| 37 | + queue.enqueue([capital[i], profits[i]], capital[i]); |
| 38 | + } |
| 39 | + |
| 40 | + for (let i = 0; i < k; i++) { |
| 41 | + while (!queue.isEmpty() && queue.front().element[0] <= w) { |
| 42 | + const element = queue.dequeue().element; |
| 43 | + descendingQueue.enqueue(element, element[1]); |
| 44 | + } |
| 45 | + if (descendingQueue.isEmpty()) { |
| 46 | + return w; |
| 47 | + } |
| 48 | + w += descendingQueue.dequeue().element[1]; |
| 49 | + } |
| 50 | + |
| 51 | + return w; |
| 52 | +}; |
0 commit comments