Grokking Graph Algorithms for Coding Interviews
Vote

0% completed

​

Solution: Cheapest Flights Within K Stops

Problem Statement

There are n cities connected by flights. You are given an array flights where flights[i] = [from<sub>i</sub>, to<sub>i</sub>, price<sub>i</sub>] indicates that there is a flight from city from<sub>i</sub> to city to<sub>i</sub> with cost price<sub>i</sub>.

Find the cheapest price from a src city to a dst city, but you are allowed to have at most k stops. If there is no such route, return -1.

Examples

Example 1:

  • Input: n = 5, flights = [[0, 1, 50], [1, 2, 50], [2, 3, 50], [3, 4, 50], [0, 4, 300]], src = 1, dst = 4, k = 2

.....

.....

.....

Like the course? Get enrolled and start learning!
Sourav Singh

Sourav Singh

· a year ago

getting time limit exceeds for following test case:

// Example 4     n4 := 13     flights4 := [][]int{{11,12,74},{1,8,91},{4,6,13},{7,6,39},{5,12,8},{0,12,54},{8,4,32},{0,11,4},{4,0,91},{11,7,64},{6,3,88},{8,5,80},{11,10,91},{10,0,60},{8,7,92},{12,6,78},{6,2,8},{4,3,54},{3,11,76},{3,12,23},{11,6,79},{6,12,36},{2,11,100},{2,5,49},{7,0,17},{5,8,95},{3,9,98},{8,10,61},{2,12,38},{5,7,58},{9,4,37},{8,6,79},{9,0,1},{2,3,12},{7,10,7},{12,10,52},{7,2,68},{12,2,100},{6,9,53},{7,4,90},{0,5,43},{11,2,52},{11,8,50},{12,4,38},{7,9,94},{2,7,38},{3,7,88},{9,12,20},{12,0,26},{10,5,38},{12,8,50},{0,2,77},{11,0,13},{9,10,76},{2,6,67},{5,6,34},{9,7,62},{5,3,67}}     src4 := 10     dst4 := 1     k4 := 10     fmt.Println(sol.findCheapestPrice(n4, flights4, src4, dst4, k4)) // Expected Output: -1

Show 1 reply

Reading Progress

0%


Vote for new content