Trains the technique from
LeetCode 787Cheapest Flights Within K StopsThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A courier company sorts parcels at hubs depots numbered 0 through hubs - 1. The array legs lists the one-way truck runs it operates: legs[i] = [start, end, price] means a parcel can ride from depot start to depot end for price euros. A run only moves in the direction listed, and no ordered pair of depots has two runs between them.
A parcel is at depot origin and must reach depot destination. Every depot it is sorted at along the way counts as a handoff, and the contract allows at most max_handoffs of them, so the parcel may ride at most max_handoffs + 1 runs. The origin and the destination are not handoffs.
Return the smallest total price of a legal itinerary, or -1 when no itinerary obeys the handoff allowance.
Example 1
Riding through depots 1 and 2 costs 150 but needs two handoffs, one more than allowed, so the parcel takes the single 400 euro run.
Example 2
With two handoffs available the chain of three cheap runs is now legal and beats the direct run.
Example 3
Depot 2 has no incoming run at all, so no itinerary reaches it and the answer is the failure value.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def cheapest_route(hubs: int, legs: list[list[int]], origin: int, destination: int, max_handoffs: int) -> int:public int cheapestRoute(int hubs, int[][] legs, int origin, int destination, int maxHandoffs)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.