Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when done. Maximise the final capital: repeatedly pick the most profitable affordable project (sorted list + max-heap).

Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when done. Maximise the final capital: repeatedly pick the most profitable affordable project (sorted list + max-heap).
import heapq
def max_capital(k, w, profits, capital):
    projects = sorted(zip(capital, profits)); h = []; i = 0
    for _ in range(k):
        while i < len(projects) and projects[i][0] <= w:
            heapq.heappush(h, -projects[i][1]); i += 1
        if not h: break
        w -= heapq.heappop(h)
    return w
p, c = [3, 5, 2, 8], [0, 3, 1, 6]
print(max_capital(2, 1, p, c), max_capital(3, 1, p, c), max_capital(2, 0, [4, 6], [1, 2]))
What is printed?
  1. A. 9 16 0
  2. B. 6 17 0
  3. C. 9 17 10
  4. D. 9 17 0

Correct answer: D. 9 17 0

Capital never decreases, so affordable projects stay affordable: push them into a max-heap as w grows and always take the best. Start w = 1: affordable profits 3, 2 → take 3 (w = 4); now the 5-profit project (needs 3) unlocks → w = 9. With k = 3 the 8-profit project (needs 6) unlocks → 17. With w = 0 nothing is affordable → 0. O(n log n + k log n).

More Coding Interview Problems questions

Exams that ask this topic