InterviewPrepKit

Home / Coding / Heap & Priority Queue

IPO

hard Original β†—
Solving tips
  • Greedy is safe because capital only grows (requirements are thresholds, not costs), so eligibility is monotone β€” once affordable, always affordable.
  • Sort projects by required capital, advance a pointer to feed every newly unlocked profit into a max-heap, and each of the k rounds pops the top profit into w.
  • Break early when the heap is empty β€” capital can be permanently stuck, and popping an empty heap would crash.
  • Target O((n + k) log n) time and O(n) space; never subtract capital[i] from w β€” it's an entry threshold, not a payment.

Problem

You start with capital w and may complete at most k projects before an IPO. Project i requires at least capital[i] capital on hand to start, and completing it adds a pure profit of profits[i] to your capital (the required capital is a threshold, not a cost β€” nothing is spent).

Projects can be done in any order, each at most once, one after another. Choose up to k projects to maximize your final capital, and return that maximum.

Examples

  • k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] β†’ 4 Only project 0 is affordable at first; finishing it raises capital to 1, unlocking projects 1 and 2. Take project 2 (profit 3) β†’ final capital 0 + 1 + 3 = 4.
  • k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] β†’ 6 Enough picks to do everything: 0 β†’ 1 β†’ 2 yields 1 + 2 + 3 = 6.
  • k = 2, w = 1, profits = [5,4], capital = [3,3] β†’ 1 No project ever becomes affordable, so the answer is just the starting capital.

Constraints

  • 1 <= k <= 10^5
  • 0 <= w <= 10^9
  • 1 <= profits.length == capital.length <= 10^5
  • 0 <= profits[i] <= 10^4, 0 <= capital[i] <= 10^9

An O(k Β· n) scan-per-pick is roughly 10^10 operations β€” the intended solution is O((n + k) log n).

Think about it first

Hint 1 Capital only ever grows. Once a project becomes affordable, it stays affordable forever β€” so the set of unlocked projects only expands.
Hint 2 Among all currently affordable projects, is there ever a reason not to take the one with the highest profit? (Taking it maximizes your capital, which can only unlock more options for later picks.)
Hint 3 Sort projects by required capital. Keep a pointer that feeds every newly affordable project's profit into a max-heap; each of the `k` rounds pops the top profit and adds it to `w`. Stop early if the heap is empty.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.