Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0514a49

Browse files
committedJan 21, 2023
Add solution #502
1 parent b53d481 commit 0514a49

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@
164164
492|[Construct the Rectangle](./0492-construct-the-rectangle.js)|Easy|
165165
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
166166
501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy|
167+
502|[IPO](./0502-ipo.js)|Hard|
167168
506|[Relative Ranks](./0506-relative-ranks.js)|Easy|
168169
509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy|
169170
520|[Detect Capital](./0520-detect-capital.js)|Easy|

‎solutions/0502-ipo.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)
Please sign in to comment.