CodingNodes / Heap / Priority Queue / IPO System design Space play · ←→ step · R restart

Problem

A company is choosing projects before going public. You start with capital w and may complete at most k distinct projects. Project i needs at least capital[i] in hand to start, and pays a profits[i] that is added to your capital as soon as it finishes.

Pick the projects so that your final capital is as large as possible, and return that capital.

Constraints

  • 1 ≤ k ≤ 100 000
  • 0 ≤ w ≤ 10^9
  • n = profits.length = capital.length, 1 ≤ n ≤ 100 000
  • 0 ≤ profits[i] ≤ 10 000
  • 0 ≤ capital[i] ≤ 10^9

Examples: pick one to animate

Solutions

TimeO(n log n + k log n) SpaceO(n)

Time: Sorting the projects by capital costs O(n log n). Every project is pushed onto the heap at most once, and each of the k rounds pops at most one profit, so the heap work is O((n + k) log n).

Space: The order array and the heap each hold up to n entries.

Capital only ever grows, so a project that is affordable now stays affordable. In each round, greedily take the most profitable project we can afford. Sort the projects by capital, and keep a max-heap of the profits of every project already affordable. A pointer j walks the sorted list and moves newly affordable projects into the heap; popping the heap gives the best one to do next. If the heap is empty, no project is affordable and we stop. The heap is an array the code manages itself, drawn here as array and tree.