C++ 0502.cpp
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
map<int, vector<short>> proj; // mincapital => profit
for (int i = 0; i < profits.size(); i++)
proj[capital[i]].push_back(profits[i]);
int result = w;
vector<short> avail;
auto last = proj.upper_bound(result);
for (auto i = proj.begin(); i != last; i++)
avail.insert(avail.end(), i->second.begin(), i->second.end());
sort(avail.begin(), avail.end());
for (int i = 0; i < k; i++)
{
if (avail.empty())
break;
auto pick = avail.back();
avail.pop_back();
auto prev = result;
result += pick;
auto from = last;
last = proj.upper_bound(result);
if (from != last)
{
for (auto j = from; j != last; j++)
{
avail.insert(avail.end(), j->second.begin(), j->second.end());
j->second.clear();
j->second.shrink_to_fit();
}
sort(avail.begin(), avail.end());
}
}
return result;
}
};
Difficulty
and has an acceptance rate of about 54% (600k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Heap (Priority Queue)
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic “maximum capital after at most k projects” problem. It first groups projects by the minimum capital required, then repeatedly selects the most profitable project that can be afforded with the current capital. The algorithm stops early when no affordable projects remain or when the allowed number of projects has been executed.
Data Preparation
A map<int, vector<short>> called proj is built where each key is a required capital amount and the associated vector stores the profits of all projects that share that requirement. The map automatically keeps the keys in ascending order, which later enables fast range queries.
map<int, vector<short>> proj; // mincapital => profit
for (int i = 0; i < profits.size(); i++)
proj[capital[i]].push_back(profits[i]);
Because the map is ordered, the subsequent upper_bound calls can locate the first entry whose capital exceeds the current wealth in logarithmic time.
Initial Availability
The variable result holds the current capital, initially set to the starting wealth w. The code then collects all projects whose capital requirement does not exceed this initial amount. It does so by iterating from the beginning of the map up to the iterator returned by proj.upper_bound(result). All profits from those entries are appended to a vector avail. After gathering, the vector is sorted in ascending order so that the most profitable project can be accessed via back().
int result = w;
vector<short> avail;
auto last = proj.upper_bound(result);
for (auto i = proj.begin(); i != last; i++)
avail.insert(avail.end(), i->second.begin(), i->second.end());
sort(avail.begin(), avail.end());
The sorting step guarantees that the highest profit is always at the end of avail, enabling O(1) extraction of the best candidate.
Iterative Selection
The main loop runs at most k times. At each iteration it first checks whether any affordable project remains; if avail is empty the loop terminates early. The most profitable affordable project is taken from the back of the sorted vector, removed, and its profit is added to result.
for (int i = 0; i < k; i++)
{
if (avail.empty())
break;
auto pick = avail.back();
avail.pop_back();
auto prev = result;
result += pick;
// ...
}
The early-exit condition handles the edge case where the initial capital is insufficient to start any project, or where the capital after a few selections still cannot unlock new projects.
Updating Available Projects
After the capital has increased, new projects may become affordable. The code recomputes the upper bound (last) for the updated capital and iterates over any newly reachable map entries. For each such entry it moves the stored profits into avail, clears the original vector, and calls shrink_to_fit() to release any excess capacity. Finally, avail is re-sorted to restore the ordering invariant.
auto from = last;
last = proj.upper_bound(result);
if (from != last)
{
for (auto j = from; j != last; j++)
{
avail.insert(avail.end(), j->second.begin(), j->second.end());
j->second.clear();
j->second.shrink_to_fit();
}
sort(avail.begin(), avail.end());
}
This block gracefully handles the situation where multiple projects share the same capital threshold, as all of them are inserted together. It also deals with the case where the capital jumps over several thresholds in one iteration, because upper_bound returns the first entry beyond the new capital, and the loop processes the whole newly reachable range.
Return Value
When the loop finishes-either because k projects have been executed, no affordable projects remain, or the capital cannot be increased further-the final capital stored in result is returned.
return result;
Edge Cases Handled
The algorithm naturally accommodates an empty input list: the map remains empty, avail stays empty, and the loop exits immediately, returning the initial capital.
When k is zero, the for-loop body never runs, so the function returns the starting wealth unchanged.
If the initial capital w is lower than the smallest required capital, proj.upper_bound(result) points to the first map entry, the initial avail vector stays empty, and the early break terminates the process without any profit accumulation.
Duplicate capital values are merged into a single map entry, and all associated profits are stored together; the insertion loop extracts them as a batch, ensuring no project is missed.
Large profit values are stored in a short vector, which fits the typical constraints of the problem; the code still works correctly because the profit is added to an int accumulator, preventing overflow of the intermediate sum.
Performance Optimizations
The use of an ordered map provides logarithmic lookup for the range of newly affordable projects after each capital increase, avoiding a full scan of all projects.
Collecting profits into a single vector<short> (avail) and keeping it sorted enables constant-time retrieval of the maximum profit via back(). The vector is only re-sorted when new elements are added, which limits sorting work to moments when the set of affordable projects actually changes.
Clearing each processed map entry and invoking shrink_to_fit() releases memory that will never be needed again, reducing the overall memory footprint during long runs.
Appending new profits with insert(avail.end(), ...) avoids repeated reallocations of intermediate containers, and the subsequent sort works on the combined data set rather than sorting each batch separately.
Overall, the algorithm balances the need for ordered access (through the map) with fast maximum-profit extraction (through the sorted vector), resulting in an efficient solution for the given constraints.
ELI5 - Simplified Explanation
Imagine playing a game where you want to go on as many rides as possible. Some rides cost a certain number of tokens to enter, and once you finish the ride, you earn even more tokens than you started with. This code is like having a little helper who manages your tokens.
First, the helper looks at all the rides available. It puts them in a neat list ordered by how many tokens are needed to enter. It keeps track of the tokens currently held in a special stash.
The helper checks which rides can be enjoyed right now because there are already enough tokens to pay the entry fee. All these accessible rides are placed into a separate group. The helper then finds the ride in that group that gives the best reward and chooses it.
After finishing that ride, the tokens are added to the stash. Because there are more tokens now, some new rides might suddenly become available. The helper looks through the list again, finds these new options, and adds them to the available group.
This cycle repeats a few times. Each time, the helper picks the most rewarding ride available, gathers the extra tokens, and checks if that new stash amount opens up any even better rides that were previously too expensive. The process keeps going until either there are no more rides left to take or the game limit is reached.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | Python | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2542: Maximum Subsequence Score
- problem 2813: Maximum Elegance of a K-Length Subsequence
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality