IPO
Difficulty: Hard · Pattern: Heap & Priority Queue · LeetCode #502
You start with capital w and may finish at most k distinct projects. Project i needs at least capital[i] to start and adds profits[i] to your capital when it's done (capital is never spent). Return your maximum final capital.
Examples
text
k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] → 4 (do 0 → w=1, then 2 → w=4)
k = 3, w = 0, profits = [1,2,3], capital = [0,1,2] → 6Hints
- Among the projects you can currently afford, which one should you do? There is no downside to picking the most profitable.
- Doing a project only increases capital, so the affordable set only grows. Sort by capital and unlock projects with a pointer.
Approach
Two structures: projects sorted by required capital (a pointer moves through them) and a max-heap of profits for the projects you can afford.
text
repeat k times:
while ptr < n and capital[ptr] <= w: push profit[ptr]; ptr++
if heap empty: break # nothing affordable, and nothing will become affordable
w += pop maxWhy is greedy safe? Picking the largest available profit gives the largest possible w after this step. Larger capital unlocks a superset of projects, so no other choice can lead to a better future (an exchange argument). O(n log n).
Complexity
Time: O(n log n + k log n). Space: O(n).
Python solution
import heapq
def findMaximizedCapital(k, w, profits, capital):
projects = sorted(zip(capital, profits))
heap, i, n = [], 0, len(projects)
for _ in range(k):
while i < n and projects[i][0] <= w:
heapq.heappush(heap, -projects[i][1])
i += 1
if not heap:
break
w -= heapq.heappop(heap)
return wJavaScript solution
function findMaximizedCapital(k, w, profits, capital) {
const idx = [...profits.keys()].sort((a, b) => capital[a] - capital[b]);
const heap = [];
const push = (x) => { heap.push(x); let i = heap.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (heap[p] >= heap[i]) break; [heap[i], heap[p]] = [heap[p], heap[i]]; i = p; } };
const pop = () => { const top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < heap.length && heap[l] > heap[m]) m = l; if (r < heap.length && heap[r] > heap[m]) m = r; if (m === i) break; [heap[i], heap[m]] = [heap[m], heap[i]]; i = m; } } return top; };
let p = 0;
for (let t = 0; t < k; t++) {
while (p < idx.length && capital[idx[p]] <= w) push(profits[idx[p++]]);
if (!heap.length) break;
w += pop();
}
return w;
}