Leet Code Daily 2024-06-15 - IPO
Solution
Greedy, always take current available project with maximum profit.
Code
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits,
vector<int>& capital) {
const int n = profits.size();
vector<pair<int, int>> projects;
for (int i = 0; i < n; i++) {
projects.push_back(make_pair(profits[i], capital[i]));
}
sort(projects.begin(), projects.end(),
[](auto& x, auto& y) { return x.second < y.second; });
priority_queue<int> available_profits;
for (int i = 0, j = 0; i < k; i++) {
while (j < n && projects[j].second <= w) {
available_profits.push(projects[j++].first);
}
if (available_profits.empty()) {
break;
}
w += available_profits.top();
available_profits.pop();
}
return w;
}
};