Python coding

Most capital after k projects

You start with capital w and may finish at most k projects, one after another. Project i can start only when your capital is at least capital[i] (starting it spends nothing), and it adds profits[i] to your capital when it finishes. Each project can be done at most once. Return the largest capital you can end with. All values are non-negative integers; profits and capital have the same length, which may be 0.

Aim for O((n + k) log n) instead of rescanning every project for each pick.

Besides the tests, one large input (4,000 projects, k = 4,000) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • most_capital(0, 2, [1,2,3], [0,1,1]) → 4
  • most_capital(0, 3, [1,2,3], [0,1,2]) → 6
  • most_capital(2, 2, [4,6,1], [3,2,0]) → 12
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Capital never goes down, so a project you can afford now stays affordable. At each pick, the best move is the most profitable project you can afford right now.

Hint 2

Sort the projects by the capital they need. Before each pick, move every newly affordable one into a max-heap of profits (negate them for heapq), then pop its root.

Hint 3

If the heap is empty, nothing is affordable and nothing will ever be: stop early, even with picks left.

Solution and why it works
pythonO((n + k) log n) · O(n)
import heapq


def most_capital(w: int, k: int, profits: list[int], capital: list[int]) -> int:
    projects = sorted(zip(capital, profits))     # by the capital each one needs
    ready = []                                   # max-heap (negated) of affordable profits
    i = 0
    for _ in range(k):
        while i < len(projects) and projects[i][0] <= w:
            heapq.heappush(ready, -projects[i][1])   # unlocked: capital never drops again
            i += 1
        if not ready:
            break                                # nothing affordable now or ever
        w -= heapq.heappop(ready)                # the most profitable affordable project
    return w

Capital only grows, so taking the most profitable affordable project never hurts: any plan that picks another one can swap it for this one and end at least as rich. Sorting by required capital lets a pointer unlock each project once, into a max-heap of profits, and each pick pops the root. Sorting is O(n log n), each unlock and pick O(log n). Traps: taking the largest profit without checking you can afford it, and rescanning every project for each pick, O(k·n).