IPO

Pick at most k projects, each with a minimum capital to start, so that the capital you end with is as large as possible.

Starting with capital w, you may complete at most k different projects, one after another. Project i can be started only while your capital is at least capital[i], and finishing it adds profits[i] to your capital. Starting a project does not use up any capital, and each project can be done only once. Return the largest capital you can end with.

Example 1
Input: k = 2, w = 0, profits = [1, 2, 3], capital = [0, 1, 1]
Output: 4
Explanation: with capital 0, only project 0 can be started. After it, the capital is 1, so project 2, with profit 3, can be started next: 1 + 3 = 4.
Example 2
Input: k = 3, w = 0, profits = [1, 2, 3], capital = [0, 1, 2]
Output: 6
Solution

The Idea

Think of a small company with some money in the bank. Each project on offer has an entry bar: the company needs at least a certain amount in the bank before it may start that project. Starting costs nothing; the money only has to be there. When a project is finished, its profit goes into the bank, and the new total may clear the bar of projects that were out of reach before.

Example 1 starts with 0 in the bank and allows 2 projects. Project 0 needs 0 and gains 1. Projects 1 and 2 both need 1, and gain 2 and 3. With 0 in the bank only project 0 is open, so it goes first and the capital becomes 1. Now projects 1 and 2 are both open, but only one more project is allowed. Which one should it be?

The one that gains more, project 2, for a final capital of 1 + 3 = 4. The same choice works in every round: among the projects you can afford right now, do the one with the biggest profit. Capital never goes down, so a project you skip stays affordable for later rounds. And the biggest profit leaves you with the most capital, which can only open more projects, never fewer.

Making the choice that looks best right now, without looking ahead, is called a greedy choice. Here it is safe, because capital never goes down and a bigger profit can only open more projects. But it raises a practical question. The set of affordable projects grows from round to round, so how do we find its biggest profit quickly each time?

Two things help. First, line the projects up by the capital they need. As capital grows, the projects that become affordable are always the next few in that line. Second, keep the profits of the affordable projects in a structure that always hands back the largest one first. Such a structure is called a max-heap. Look at the picture below.

Example 1 in two rounds. With capital 0, only project 0 is affordable; its profit 1 goes into the max-heap and is taken, so capital becomes 1. With capital 1, projects 1 and 2 become affordable; the heap holds 3 and 2, the top 3 is taken, and capital becomes 4.

In the row labelled Round 1, the capital is 0, so only project 0 turns teal: it is newly affordable. Its profit, 1, goes into the max-heap of profits, and taking the top gives capital 0 + 1 = 1. In the row labelled Round 2, project 0 is done, and capital 1 makes projects 1 and 2 affordable. Their profits, 3 and 2, join the heap, 3 sits on top, and taking it gives capital 1 + 3 = 4.

Profit 2 stays in the heap. If a third round were allowed, it would be ready there without looking at the projects again.

Solution Approach

Turning that idea into code means settling four things: why rescanning all projects is slow, how to unlock projects by capital, how to keep the largest profit within reach, and when to stop.

Rescanning every project each round

What would the simple way look like? Each round, walk over all n projects (n is the length of profits), skip the ones already done or not yet affordable, and pick the biggest profit among the rest. That is correct, but every one of the k rounds costs n checks. With 100,000 projects and 100,000 rounds, that is 1010 checks, most of them repeating what the round before already saw.

Unlocking projects in order of capital

How do we avoid looking at a project twice? Sort the projects by the capital they need, and keep a marker on the first one that is not yet affordable. When the capital grows, the marker moves forward over every project the capital now covers, unlocking it, and it never moves back. Over all the rounds, it passes each project once.

The profits and capital needs sit in two separate arrays, so the code sorts project numbers, not projects. An array of indexes 0, 1, 2, ... is sorted by capital[i], and the two arrays stay as they are.

Keeping the largest profit on top

Which Java class gives the largest profit quickly? PriorityQueue, in java.util, keeps its items as a heap. By default it is a min-heap: poll() removes and returns the smallest item. Passing the comparator Collections.reverseOrder() flips the order, so the largest item comes out first:

Java
PriorityQueue<Integer> affordable = new PriorityQueue<>(Collections.reverseOrder());

In Round 2 of the picture, this queue holds 3 and 2, and poll() returns 3. Adding a profit and removing the top each take about log n steps, where n is the number of projects, because the heap only reorders one path from its top to its bottom.

Stopping when nothing is affordable

What if no project can be started? Then the heap is empty, and since the capital did not change, the next round would find it empty too. The loop stops and returns the capital it has. The same check ends the loop when k is larger than the number of projects: once every project is done, the heap is empty.

Java Solution

The method findMaximizedCapital works in these steps:

  1. First, build byCapital, an array of the project indexes 0 to n - 1, and sort it with Arrays.sort and a comparator on capital[i]. It is an Integer[], not an int[], because Java's sort with a comparator only works on arrays of objects.
  2. Create affordable, the max-heap of profits, as a PriorityQueue with Collections.reverseOrder(). Set next, the marker into byCapital, to 0.
  3. Run a loop of at most k rounds. Inside it, a while loop moves next forward as long as the project it points at needs no more than w, adding that project's profit to affordable.
  4. If affordable is still empty, no project can be started, so the rounds stop with break.
  5. Otherwise, affordable.poll() removes the largest profit, and it is added to w. After the last round, the method returns w.

The main method runs both examples, a start where all three projects are affordable but only one round is allowed, a project that is never affordable, and 10 rounds for only three projects.

Java
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;

public class IPO {

    public static int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        int n = profits.length;
        Integer[] byCapital = new Integer[n];
        for (int i = 0; i < n; i++) {
            byCapital[i] = i;
        }
        Arrays.sort(byCapital, (a, b) -> Integer.compare(capital[a], capital[b]));

        // max-heap: the largest profit sits on top
        PriorityQueue<Integer> affordable = new PriorityQueue<>(Collections.reverseOrder());
        int next = 0;                         // first project, in capital order, not yet unlocked
        for (int round = 0; round < k; round++) {
            while (next < n && capital[byCapital[next]] <= w) {
                affordable.add(profits[byCapital[next]]);   // w now covers this project
                next++;
            }
            if (affordable.isEmpty()) {
                break;                        // no project can be started, now or later
            }
            w += affordable.poll();           // do the most profitable affordable project
        }
        return w;
    }

    public static void main(String[] args) {
        System.out.println(findMaximizedCapital(2, 0, new int[] {1, 2, 3}, new int[] {0, 1, 1}));
        System.out.println(findMaximizedCapital(3, 0, new int[] {1, 2, 3}, new int[] {0, 1, 2}));
        System.out.println(findMaximizedCapital(1, 2, new int[] {1, 5, 3}, new int[] {0, 2, 1}));
        System.out.println(findMaximizedCapital(2, 0, new int[] {5}, new int[] {5}));
        System.out.println(findMaximizedCapital(10, 0, new int[] {1, 2, 3}, new int[] {0, 1, 2}));
    }
}

Running it prints:

Output
4
6
7
0
6

The 4 and the 6 at the top match Examples 1 and 2. In Example 2 each round opens exactly one new project: capital 0 opens project 0, capital 1 opens project 1, and capital 3 opens project 2, so the capital goes 1, 3, 6.

The 7 comes from a start with capital 2, where all three projects are affordable at once. The single round takes profit 5, not 1 or 3, because it sits on top of the heap. The 0 comes from a single project that needs 5: the heap is empty in the first round, so the loop stops with the starting capital.

The last line, 6, allows 10 rounds for three projects. After the third round the heap is empty, so the loop stops with the same 6 as Example 2.

The isEmpty() check also keeps the method from crashing. On an empty heap, poll() returns null, and Java cannot add null to the int w. With the check removed, the program prints 4, 6 and 7, then stops at the never-affordable project with a NullPointerException whose message says that the return value of PriorityQueue.poll() is null.

Complexity

The work is the sort, plus one heap insert for each project and one heap removal for each round.

  • Time: O(n log n + k log n), because the sort takes about n log n steps, each project enters the heap at most once at log n, and each of at most k rounds removes the top at log n.
  • Space: O(n), because byCapital holds n indexes and the heap holds all n profits when every project is affordable from the start.

A sorted list feeding a heap is also the core of Maximum Subsequence Score.