Skip to content

Commit 7034691

Browse files
committed
java: Create cheapest flights within K stops
1 parent 897c000 commit 7034691

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time Complexity O(k * n) | Space Complexity O(n)
2+
class Solution {
3+
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
4+
5+
// initialize an array with max value of size n
6+
int[] prices = new int[n];
7+
Arrays.fill(prices, Integer.MAX_VALUE);
8+
9+
// price from source to source is always 0
10+
prices[src] = 0;
11+
12+
for (int i = 0; i <= k; i++){
13+
14+
// make a copy of prices
15+
int[] temp = new int[n];
16+
temp = Arrays.copyOf(prices, prices.length);
17+
18+
// loop through flights
19+
for(int j = 0; j < flights.length; j ++){
20+
21+
int s = flights[j][0]; // from
22+
int d = flights[j][1]; // to
23+
int p = flights[j][2]; // price
24+
25+
if (prices[s] == Integer.MAX_VALUE){
26+
continue;
27+
}
28+
29+
if (prices[s] + p < temp[d]){
30+
temp[d] = prices[s] + p;
31+
}
32+
33+
}
34+
35+
// set prices to temp
36+
prices = temp;
37+
}
38+
39+
40+
if (prices[dst] != Integer.MAX_VALUE){
41+
return prices[dst];
42+
}
43+
44+
return -1;
45+
46+
}
47+
}

0 commit comments

Comments
 (0)