Cheapest Flights Within K Stops
Medium Advanced graphs AI round
The n cities are numbered from 0 to n - 1. Each entry [from, to, price] of flights is a one-way flight from city from to city to that costs price.
A trip from src to dst takes flights one after another, each leaving from the city where the one before landed. Each city it lands in before dst is a stop, so a trip with k stops takes k + 1 flights.
Return the cheapest price of a trip from src to dst with at most k stops, or -1 if there is none. When src and dst are the same city, no flight is needed and the price is 0.
Example 1
The cheapest trip, 0 → 2 → 3 → 4 for 30, stops at 2 and 3: one stop too many. With one stop, 0 → 1 → 4 costs 80, less than the direct flight for 100.
Example 2
Example 3
Constraints
1 ≤ n ≤ 1000 ≤ flights.length ≤ 2000flights[i] = [from, to, price], with0 ≤ from, to < n,from ≠ toand1 ≤ price ≤ 10⁴- No two flights go from the same city to the same city
0 ≤ src, dst < n0 ≤ k < n
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
More Advanced graphs
- Course ScheduleAI round · Medium
- Longest Increasing Path in a MatrixAI round · Hard
- Alien DictionaryHard
- Course Schedule IIMedium
- Evaluate DivisionMedium