Skip to the code
+25 XP

#463 Cheapest Itinerary With Limited Layovers

medium

A travel site searches n cities numbered 0 to n - 1. Each flights[i] = [from, to, price] is a one-way flight. Travelers set a limit k on layovers: a trip may stop in at most k cities between src and dst, so it uses at most k + 1 flights.

Write cheapestTrip(n, flights, src, dst, k) that returns the lowest total price from src to dst within the layover limit, or -1 if there is no such trip. src and dst are different.

Example 1

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

With at most 1 layover, the options are the direct flight (500) and 0 → 1 → 3 (700).

Example 2

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

Two layovers allow 0 → 1 → 2 → 3 for 300.

Constraints

  • 2 <= n <= 100
  • 0 <= flights.length <= 5000
  • 1 <= price <= 10^4
  • 0 <= k < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).