Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths).

Problem: Maximum flow from s = 0 to t = 5 with Edmonds–Karp (BFS augmenting paths).
from collections import deque
cap = [[0]*6 for _ in range(6)]
for u, v, c in [(0,1,10),(0,2,10),(1,2,2),(1,3,4),(1,4,8),(2,4,9),(3,5,10),(4,3,6),(4,5,10)]:
    cap[u][v] = c
def maxflow(s, t):
    flow = 0
    while True:
        par = [-1] * 6; par[s] = s; q = deque([s])
        while q and par[t] == -1:
            u = q.popleft()
            for v in range(6):
                if par[v] == -1 and cap[u][v] > 0: par[v] = u; q.append(v)
        if par[t] == -1: return flow
        b, v = float('inf'), t
        while v != s: b = min(b, cap[par[v]][v]); v = par[v]
        v = t
        while v != s: cap[par[v]][v] -= b; cap[v][par[v]] += b; v = par[v]
        flow += b
print(maxflow(0, 5))
What is printed?
  1. A. 20
  2. B. 21
  3. C. 4
  4. D. 19

Correct answer: D. 19

Node 2 can receive 10 from the source but forward only 9 (to 4), so the cut 0→1 (10) + 2→4 (9) = 19 is the minimum and Edmonds–Karp reaches it. The source's out-capacity (and the sink's in-capacity) is 20, the cut around {0, 1, 2} is 21 but not minimal, and stopping after the first BFS path 0→1→3→5 gives only 4.

More Coding Interview Problems questions

Exams that ask this topic