502. IPO
Problem
You start with capital w and may finish at most k projects. Project i needs at least capital[i] to start and adds profits[i] to your capital when done (the capital isn't spent). Return the largest capital you can end with.
Example: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1] → 4
Constraints: up to 10⁵ projects.
Sort projects by capital. Each round, push every newly affordable project's profit into a max-heap and take the best one. Repeat k times.
Complexity: O(n log n + k log n).
class Solution:
def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
projects = sorted(zip(capital, profits))
h, i = [], 0
for _ in range(k):
while i < len(projects) and projects[i][0] <= w:
heappush(h, -projects[i][1])
i += 1
if not h:
break
w -= heappop(h)
return w
assert Solution().findMaximizedCapital(2, 0, [1, 2, 3], [0, 1, 1]) == 4
assert Solution().findMaximizedCapital(3, 0, [1, 2, 3], [0, 1, 2]) == 6
class Solution {
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
int n = profits.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> capital[a] - capital[b]);
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
int i = 0;
while (k-- > 0) {
while (i < n && capital[idx[i]] <= w) pq.add(profits[idx[i++]]);
if (pq.isEmpty()) break;
w += pq.poll();
}
return w;
}
}
type MaxHeap []int
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func findMaximizedCapital(k int, w int, profits []int, capital []int) int {
idx := make([]int, len(profits))
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(a, b int) bool { return capital[idx[a]] < capital[idx[b]] })
h, i := &MaxHeap{}, 0
for ; k > 0; k-- {
for i < len(idx) && capital[idx[i]] <= w { // newly affordable projects
heap.Push(h, profits[idx[i]])
i++
}
if h.Len() == 0 {
break
}
w += heap.Pop(h).(int) // take the most profitable one
}
return w
}