Code RoomMinimum cost flow
HardPrep Room Coding #1451

Minimum cost flow

CodingAlgorithms & data structuresSenior–Staff~45 min

You are given a directed flow network on n nodes as edges [u, v, cap, cost] (capacity and per-unit cost are non-negative integers), a source s, a target t, and an integer K. Find the minimum total cost to send EXACTLY K units of flow from s to t, where each unit traversing an edge pays that edge's cost. Return the minimum cost, or -1 if it is impossible to route K units. Constraints: up to 50 nodes; small capacities and K (each <= a few hundred).

Implement
min_cost_flow(n: int, edges: list[list[int]], s: int, t: int, K: int) → int
Examples
in[4,[[0,1,2,1],[0,2,2,2],[1,3,2,1],[2,3,2,1]],0,3,3]out7
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 45 min
InputExpectedGot
[4,[[0,1,2,1],[0,2,2,2],[1,3,2,1],[2,3,2,1]],0,3,3]7not run yetsample