InferenceAI

Enter at least two characters to search.

Start free

Cheapest Route With K Stops

hardGraphs40 min50 XP

flights[i] = [from, to, price]. Return the cheapest price from src to dst using at most k intermediate stops, or -1 if there is no such route.

Requirements

  • Bellman–Ford limited to k+1k + 1 rounds, copying the distance array each round.

Examples

EXAMPLE WALKTHROUGHone stop

A guided view of the published example, not a trace of your code.

INPUT[4,[[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]],0,3,1]
TASKcheapest_route_k_stops()
EXPECTED OUTPUT700

Start with the input values shown in this example.

Example 1 of 3

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

Explanation: one stop

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1

Output: 200

Explanation: cheaper with a stop

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0

Output: 500

Explanation: direct only

Hint 1

Each round relaxes every flight using the previous round's prices, which caps the number of edges used.

Topics

DSAGraphsPython