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 wkicapital[i]profits[i]
Example 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
Output: 6
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.
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
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]
Keeping the largest profit on top
Which Java class gives the largest profit quickly? PriorityQueuejava.utilpoll()Collections.reverseOrder()
PriorityQueue<Integer> affordable = new PriorityQueue<>(Collections.reverseOrder());
In Round 2 of the picture, this queue holds 3 and 2, and poll()
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
- First, build
, an array of the project indexes 0 to n - 1, and sort it withbyCapital and a comparator onArrays.sort . It is ancapital[i] , not anInteger[] , because Java's sort with a comparator only works on arrays of objects.int[] - Create
, the max-heap of profits, as aaffordable withPriorityQueue . SetCollections.reverseOrder() , the marker intonext , to 0.byCapital - Run a loop of at most
rounds. Inside it, ak loop moveswhile forward as long as the project it points at needs no more thannext , adding that project's profit tow .affordable - If
is still empty, no project can be started, so the rounds stop withaffordable .break - Otherwise,
removes the largest profit, and it is added toaffordable.poll() . After the last round, the method returnsw .w
The main
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:
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()poll()nullnullintwNullPointerExceptionPriorityQueue.poll()
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
holds n indexes and the heap holds all n profits when every project is affordable from the start.byCapital
A sorted list feeding a heap is also the core of