DSA Heaps

IPO (Maximize Capital)

Pick up to k profitable projects with starting capital — greedy with a min-heap of affordable projects and a max-heap of profits.

Hard
Time O(n log n) Space O(n)
LeetCode
5 min read
heaps greedy

Problem#

You have w capital. n projects exist; project i requires capital capital[i] and yields profit profits[i]. Pick at most k projects (each at most once) to maximize final capital.

Examples#

  • k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]4

Constraints#

  • 1 <= k <= 10^5, 0 <= w <= 10^9.

Approach#

Sort projects by capital ascending. At each round, push all newly-affordable projects into a max-heap by profit; pop the most profitable one and add to w. Repeat k times or until no project is affordable.

Solution#

IPO
class Solution {
public:
int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
int n = profits.size();
vector<pair<int,int>> p(n);
for (int i = 0; i < n; ++i) p[i] = {capital[i], profits[i]};
sort(p.begin(), p.end());
priority_queue<int> pq;
int i = 0;
while (k--) {
while (i < n && p[i].first <= w) pq.push(p[i++].second);
if (pq.empty()) break;
w += pq.top(); pq.pop();
}
return w;
}
};

Editorial#

The greedy choice is “among projects I can currently afford, do the most profitable one”. After acquiring profit, more projects become affordable — push them into the heap. Sorting by capital lets us unlock projects in a single forward sweep.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.