Greedy Algorithms8 sections · 316 units
Open in Course

IPO - Implementation

The code

Here is the solution:

function findMaximizedCapital(k, W, profits, capital)
 projects := list of (capital[i], profits[i])
 sort projects by capital ascending
 availableHeap := max-heap by profit
 i := 0
 for round from 1 to k
 while i < n and projects[i].capital <= W
 availableHeap.push(projects[i].profit)
 i := i + 1
 if availableHeap is empty then
 break
 W := W + availableHeap.pop()
 return W

Time: O(nlogn)O(n \log n) for sorting and heap operations. Space: O(n)O(n).

Each round, add all affordable projects, then take the most profitable.