IPO solution explained
IPO asks for the most capital you can end with after finishing at most k projects, where each project needs a minimum amount of capital to start and adds its profit when done. The greedy answer: sort projects by required capital, and k times move every project you can now afford into a max-heap of profits, then take the largest. That is O(n log n + k log n), and it is optimal because capital only ever grows.
By Evin JohnPublished 8 min read
The problem, in plain terms
A small company wants to grow before going public. It starts with w units of capital and has time for at most k projects, done one after another. Project i can only be started if current capital is at least need[i]; starting it does not spend anything, and finishing it adds gain[i] to capital. Each project can be done at most once. Choose the projects and their order to make final capital as large as possible, and return it.
Case A: w = 1, k = 2
project 0 1 2 3
need 0 1 1 4
gain 2 3 1 5
round 1: capital 1, can start 0, 1, 2 take 1 (gain 3) capital 4
round 2: capital 4, project 3 unlocks take 3 (gain 5) capital 9
answer: 9
Case B: w = 0, k = 3, need = [1, 2], gain = [5, 5]
nothing can be started at capital 0 answer: 0Case A shows why order matters. Project 3 is the most profitable, but it is locked at the start. Taking the best project available now (gain 3) is exactly what unlocks it. Taking project 0 first would have reached only capital 3 and still left project 3 locked for round 2, ending at 6.
Points to confirm: is starting a project free, so only the threshold matters? (Yes here.) Can a profit be zero? Can k exceed the number of projects? What should happen when nothing is affordable, return w unchanged? All of these have simple answers, but asking them shows you read the rules.
Why it is a good interview question
It looks like a knapsack problem, and candidates who reach for dynamic programming burn time. The real test is spotting the property that makes greedy safe, then implementing the two-structure pattern cleanly: one ordering decides when an item becomes eligible, another decides which eligible item is best. Expect to be asked why greedy is correct, not just to code it.
Brute force: rescan every round
Before any proof, here is the direct version of the greedy rule. Each round, scan all unfinished projects, keep the affordable ones, and take the one with the largest gain. It is O(k × n) and is handy for checking the heap version on small inputs.
def final_capital_scan(k, w, need, gain):
done = [False] * len(need)
for _ in range(k):
best = -1
for i in range(len(need)):
if not done[i] and need[i] <= w and (best < 0 or gain[i] > gain[best]):
best = i
if best < 0:
break
done[best] = True
w += gain[best]
return wA truly exhaustive search, trying every subset of at most k projects in every feasible order, is exponential. It was still worth writing for the test harness behind this page, because it checks the greedy claim itself rather than just one implementation of it.
Why greedy is optimal
Capital never goes down, because profits are zero or more and starting costs nothing. Suppose an optimal plan's first project is not the most profitable affordable one, call that best project B. Replace the first project with B. After that step capital is at least as high as in the optimal plan, so every later project in the plan is still affordable. If B appears later in the plan, swap the two instead: B moves to the front, and the old first project takes B's slot, which it can still afford because it was affordable at the very start. Either way the total gain does not drop. Repeat for each round and you reach the greedy plan with no loss.
Optimal approach: sorted thresholds and a max-heap
Sort projects by need. Walk them with a pointer. In each of the k rounds, push the gain of every project whose need is now within reach onto a max-heap, then pop the largest gain and add it to capital. Projects are pushed in threshold order and capital only rises, so the pointer never moves backward and each project enters the heap at most once.
import heapq
def final_capital(k, w, need, gain):
projects = sorted(zip(need, gain))
open_gains = [] # negated, because heapq is a min-heap
nxt = 0
for _ in range(k):
while nxt < len(projects) and projects[nxt][0] <= w:
heapq.heappush(open_gains, -projects[nxt][1])
nxt += 1
if not open_gains:
break # nothing affordable now, so nothing ever will be
w -= heapq.heappop(open_gains)
return wThe early break matters for speed when k is huge and for correctness of the reasoning: if the heap is empty, capital cannot change, so no later round can unlock anything. In C++ the default priority_queue is already a max-heap, which makes the code shorter.
#include <algorithm>
#include <queue>
#include <utility>
#include <vector>
long long finalCapital(int k, long long w, const std::vector<int>& need,
const std::vector<int>& gain) {
std::vector<std::pair<int, int>> projects;
for (size_t i = 0; i < need.size(); ++i) projects.push_back({need[i], gain[i]});
std::sort(projects.begin(), projects.end());
std::priority_queue<int> open; // largest gain on top
size_t nxt = 0;
for (int round = 0; round < k; ++round) {
while (nxt < projects.size() && projects[nxt].first <= w) {
open.push(projects[nxt].second);
++nxt;
}
if (open.empty()) break;
w += open.top();
open.pop();
}
return w;
}Complexity summary
| Approach | Time | Extra memory | Note |
|---|---|---|---|
| Every subset in every order | Exponential | O(n) | Only for checking the greedy claim |
| Greedy by full scan | O(k × n) | O(n) | Same answers, slower |
| Sort plus max-heap | O(n log n + k log n) | O(n) | Expected answer |
Edge cases to try
- Nothing affordable at the start: return w.
- k larger than the number of projects: the loop must stop when the heap runs dry.
- Projects with gain 0: harmless, but they still use up a round if picked.
- Every project affordable from the start: the answer is w plus the k largest gains.
- A project that only unlocks after two others: checks that the pointer keeps advancing across rounds.
Mistakes to avoid
- Sorting by gain and taking the top k, ignoring that some are locked.
- Sorting by need and taking projects in that order, which picks cheap but poor projects.
- Pushing all projects into the heap at once and filtering when popping, which can lose locked projects that are popped too early.
- Rebuilding the heap from scratch every round, quietly turning the solution into O(k × n log n).
- Subtracting need from capital, as if starting a project cost money. In this problem it does not.
Follow-ups
- Starting a project spends its cost. The monotonic argument breaks (capital can fall), and the problem becomes much harder; for small inputs, search or dynamic programming over states is the honest answer.
- Return which projects were chosen. Store (gain, index) in the heap instead of just the gain.
- Profits can be negative. Simply never pick a negative one, since doing fewer than k projects is allowed.
- Projects have durations and a deadline. Now you are in scheduling territory, closer to Single-Threaded CPU or to course-scheduling greedy problems.
How to explain it out loud
Fictional example
- Candidate
- The key fact is that capital only goes up. Finishing any project never makes another project unaffordable.
- Candidate
- So in each round, the best move is the most profitable project I can start now. Anything else leaves me with less capital and no more options.
- Interviewer
- How do you find that project quickly?
- Candidate
- Sort projects by required capital. As capital grows I unlock them in that order and push their profits into a max-heap, then pop the top. Each project is pushed once, so it is O(n log n) plus O(k log n).
- Candidate
- If the heap is ever empty, I stop, because capital will not change again.
Related problems
Single-Threaded CPU uses the same unlock-then-choose structure with arrival times instead of thresholds. Minimum Cost to Hire K Workers sorts by one quantity and keeps a heap of another to optimize a product. Furthest Building You Can Reach is another greedy choice backed by a heap. Top K Frequent Elements is a simpler warm-up on keeping the best few items.
Practicing it with Natively
IPO rewards a crisp argument more than clever code, so practice explaining the proof until it fits in four sentences. On Mac or Windows, Natively can read the problem from a screenshot during practice and outline the two-structure greedy, and it transcribes your mock answer so you can check whether you justified the greedy step or just asserted it. The AI interview assistant page has the details.
Questions people ask
How do you solve the IPO problem?
Sort projects by required capital. For each of the k rounds, push the profit of every project you can now afford into a max-heap, then pop the largest profit and add it to your capital. Stop early if the heap is empty.
Why is greedy correct for IPO?
Starting a project costs nothing and profits are never negative, so capital only grows. Taking the most profitable affordable project leaves you with at least as much capital as any other choice, so it never removes a later option.
What is the time complexity of IPO?
O(n log n) to sort plus O(k log n) for the heap operations, with O(n) extra memory. A version that rescans all projects each round is O(k × n).
Is IPO a knapsack problem?
It looks like one, but no dynamic programming is needed. Because capital never decreases, the greedy choice is safe, which is the insight interviewers want to hear.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
