Cheapest flight within k stops
Mediumgraphshortest pathbellman-forddynamic programming
There are n cities. Each [from, to, price] in flights is a one-way flight. Return the cheapest price from src to dst with at most k stops in between (at most k + 1 flights), or -1 if there's none.
Example 1
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700
0 → 1 → 3 costs 700. 0 → 1 → 2 → 3 is cheaper (400) but has two stops.
Example 2
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 Output: 200
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ flights.length ≤ 4000
- 1 ≤ price ≤ 10⁴
- 0 ≤ k < n
- src ≠ dst
Submit checks your solution against 8 tests, including hidden ones.
/**
* @param {int} n
* @param {int[][]} flights
* @param {int} src
* @param {int} dst
* @param {int} k
* @return {int}
*/
function findCheapestPrice(n, flights, src, dst, k) {
}