#787

Cheapest Flights Within K Stops

Medium Bellman-Ford with k+1 rounds

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find the cheapest price from src to dst using at most k stops (k + 1 flights), or -1.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the cheapest route using at most k stops.

Why this works: Bellman-Ford's i-th round finds the best routes with at most i flights. Run k + 1 rounds, reading the previous round's prices.

Example: 0→1 (100), 1→2 (100), 0→2 (500), k = 1

round 1: price 1 = 100, price 2 = 500round 2: price 2 = min(500, 100+100) = 200

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Updating the same array within a round, which lets one round use more than one extra flight.

Solve on LeetCode ↗
Complexity
  • Time: O(k · E).
  • Space: O(V).
Topic: Graphs
🎬 Episodes 74–85: video coming soon