Skip to content
Problem 502 · LeetCode 502(opens in a new tab)

IPO

HardGreedy algorithms

You start with w units of money and may complete at most k different projects, one after another. Project i can only be started if your money is at least capital[i]. Finishing it adds profits[i] to your money; the capital is not spent.

Choose the projects and their order to end with as much money as possible, and return that amount.

Example 1

Input:  k = 2, w = 1, profits = [3, 5, 2, 6], capital = [0, 2, 1, 4]
Output: 10
Why:    take profit 3 (w = 4), which unlocks the project worth 6
2 more examples and the constraints

Example 2

Input:  k = 3, w = 0, profits = [4, 1], capital = [0, 6]
Output: 4
Why:    after the first project, 6 is still out of reach

Example 3

Input:  k = 1, w = 5, profits = [2, 9, 7], capital = [5, 6, 3]
Output: 12
Why:    9 needs 6, so the best affordable profit is 7

Constraints

  • 1 ≤ k ≤ 100,000 and 1 ≤ n ≤ 100,000, where n is the length of profits and of capital
  • 0 ≤ w ≤ 1,000,000,000
  • 0 ≤ profits[i] ≤ 10,000 and 0 ≤ capital[i] ≤ 1,000,000,000
  • The answer fits in a 32-bit signed integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Rescan every roundO(k·n)
  2. Sort + max-heapO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for k = n = 100,000Verdict
Rescan every roundO(k·n)
Mention it, then move on
Sort + max-heapO(n log n + k log n)
Best; each project handled once

n = number of projects, k = how many you may complete.

Edge cases to test

  • Nothing affordable. k = 2, w = 0, one project that needs 1: the answer is w itself, 0.
  • k larger than n. You cannot repeat a project, so stop when the heap runs dry.
  • Zero profits. Taking a project worth 0 changes nothing, and that is fine.
  • Big numbers. w can start at 1,000,000,000; the sum still fits in 32 bits by the constraints.

Common mistakes

  • Subtracting the capital from w. Capital is a threshold, not a cost.
  • Picking the cheapest project instead of the most profitable affordable one.
  • Looping all k rounds after the heap is empty, popping from an empty heap.

How to talk through it

  1. 1Clarify. Is capital spent or only required? Can a project be done twice? Can profits be zero?
  2. 2Argue the greedy. Money only grows, so the biggest affordable profit now is never a worse choice.
  3. 3Give the brute force. Scan every project each round: O(k·n), too slow at 100,000 each.
  4. 4Speed up the choice. Sort by capital, push newly affordable profits into a max-heap, pop the top each round.
  5. 5Test out loud. Run a case where nothing is affordable and one where k is larger than n.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?