Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.
You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.
Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.
//code
{#include <map>
#include <vector>
#include <algorithm> // for sort
using namespace std;
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
map<int, vector<int>> m;
// Populate the map with profits sorted by capital
for (int i = 0; i < capital.size(); ++i) {
m[capital[i]].push_back(profits[i]);
}
// Sort profits for each capital in descending order
for (auto it = m.begin(); it != m.end(); ++it) {
sort(it->second.begin(), it->second.end(), greater<int>());
}
// Select k projects to maximize capital
for (int i = 0; i < k; ++i) {
// Iterate through each capital level and select the project with maximum profit
for (auto rit = m.rbegin(); rit != m.rend(); ++rit) { // Reverse iteration
int capital_level = rit->first;
if (capital_level <= w && !rit->second.empty()) {
int max_profit = rit->second.front();
w += max_profit; // Add the profit of the selected project
rit->second.erase(rit->second.begin()); // Remove the selected project from consideration
break; // Move to the next iteration of selecting k projects
}
}
}
return w;
}
};
}
Anurag Shivam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.