Cheapest Flight Within K Stops
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
There are n airports numbered 0 to n - 1. flights[i] = [a, b, price] is a direct flight from airport a to
airport b costing price (the reverse direction is a separate flight, if any).
Travel from src to dst with at most k intermediate stops, i.e. taking at most k + 1 flights. Return the cheapest
total price, or -1 if it is impossible.
Examples
| n | flights | src | dst | k | result |
|---|---|---|---|---|---|
4 | [[0, 1, 100], [1, 2, 100], [2, 3, 100], [0, 2, 650], [1, 3, 600]] | 0 | 3 | 1 | 700 |
4 | [[0, 1, 100], [1, 2, 100], [2, 3, 100], [0, 2, 650], [1, 3, 600]] | 0 | 3 | 2 | 300 |
3 | [[0, 1, 5], [1, 2, 5]] | 0 | 2 | 0 | -1 |
Example 1 — With one stop: 0 → 1 → 3 costs 700 and 0 → 2 → 3 costs 750.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(n: int, flights: int[][], src: int, dst: int, k: int) → int
Constraints
-
n -
flights.length,a,b,ab,price; parallel flights may appear -
src,dst,srcdst,k
Expected complexity
- Time
- O(K * (N + M))
- Space
- O(N + M)
Examples
| n | flights | src | dst | k | Expected |
|---|---|---|---|---|---|
4 | [[0,1,100],[1,2,100],[2,3,100],[0,2,650],[1,3,600]] | 0 | 3 | 1 | 700 |
4 | [[0,1,100],[1,2,100],[2,3,100],[0,2,650],[1,3,600]] | 0 | 3 | 2 | 300 |
3 | [[0,1,5],[1,2,5]] | 0 | 2 | 0 | -1 |
Hint
Hint
Plain Dijkstra ignores the flight-count limit. Run Bellman–Ford for exactly k + 1 rounds, relaxing every flight from the
previous round's costs only (a copy), so each round adds at most one flight; cost[dst] after the last round is the
answer. Scanning an price table in every round is and exceeds the time limit;
is enough.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 4 | verdict only |