SDE & MLE Prep

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