Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IPO Editorial #5071

Merged
merged 12 commits into from
Jan 23, 2025
4 changes: 2 additions & 2 deletions content/3_Silver/Greedy_Sorting.problems.json
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,15 @@
}
},
{
"uniqueId": "lc-IPO",
"uniqueId": "leetcode-502",
"name": "IPO",
"url": "https://leetcode.com/problems/ipo",
"source": "LC",
"difficulty": "Normal",
"isStarred": false,
"tags": ["Greedy", "Sorting", "Priority Queue"],
"solutionMetadata": {
"kind": "none"
"kind": "internal"
}
},
{
Expand Down
91 changes: 91 additions & 0 deletions solutions/silver/leetcode-502.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
---
id: leetcode-502
source: LC
title: IPO
author: Rameez Parwez
---

## Explanation

We can solve this problem using a greedy approach.

The idea is to prioritize projects that offer the highest profit.
At the same time, we ensure that the projects we choose can be started with the capital we currently have.

## Implementation

**Time Complexity:** $ \mathcal{O} (N \log N)$

<LanguageSection>
<CPPSection>

```cpp
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int> &profits, vector<int> &capital) {
const int n = (int)profits.size();

vector<pair<int, int>> projects(n);
for (int i = 0; i < n; i++) { projects[i] = {capital[i], profits[i]}; }
sort(begin(projects), end(projects));

priority_queue<int> pq;
int j = 0;
while (j < n && k > 0) {
if (projects[j].first <= w) {
pq.push(projects[j].second);
j++;
} else {
if (pq.empty()) { return w; }
w += pq.top();
pq.pop();
k--;
}
}
while (k > 0 && !pq.empty()) {
w += pq.top();
pq.pop();
k--;
}

return w;
}
};
```

</CPPSection>
<PySection>

```py
import heapq

SansPapyrus683 marked this conversation as resolved.
Show resolved Hide resolved

class Solution:
def findMaximizedCapital(
self, k: int, w: int, profits: List[int], capital: List[int]
) -> int:
n = len(profits)
projects = sorted((capital[i], profits[i]) for i in range(n))

j = 0
pq = []
while j < n and k > 0:
if projects[j][0] <= w:
heapq.heappush(pq, -projects[j][1])
j += 1
else:
if not pq:
return w

w += -heapq.heappop(pq)
k -= 1

while k > 0 and pq:
w += -heapq.heappop(pq)
k -= 1

return w
```

</PySection>
</LanguageSection>
Loading