Skip to content

Commit 72009f5

Browse files
committed
Add solution #787
1 parent 73e0b95 commit 72009f5

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,7 @@
597597
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
598598
785|[Is Graph Bipartite?](./0785-is-graph-bipartite.js)|Medium|
599599
786|[K-th Smallest Prime Fraction](./0786-k-th-smallest-prime-fraction.js)|Medium|
600+
787|[Cheapest Flights Within K Stops](./0787-cheapest-flights-within-k-stops.js)|Medium|
600601
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
601602
791|[Custom Sort String](./0791-custom-sort-string.js)|Medium|
602603
796|[Rotate String](./0796-rotate-string.js)|Easy|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 787. Cheapest Flights Within K Stops
3+
* https://leetcode.com/problems/cheapest-flights-within-k-stops/
4+
* Difficulty: Medium
5+
*
6+
* There are n cities connected by some number of flights. You are given an array flights where
7+
* flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city
8+
* toi with cost pricei.
9+
*
10+
* You are also given three integers src, dst, and k, return the cheapest price from src to dst
11+
* with at most k stops. If there is no such route, return -1.
12+
*/
13+
14+
/**
15+
* @param {number} n
16+
* @param {number[][]} flights
17+
* @param {number} src
18+
* @param {number} dst
19+
* @param {number} k
20+
* @return {number}
21+
*/
22+
var findCheapestPrice = function(n, flights, src, dst, k) {
23+
const MAX_INT = Number.MAX_SAFE_INTEGER;
24+
let prices = new Array(n).fill(MAX_INT);
25+
prices[src] = 0;
26+
27+
for (let i = 0; i <= k; i++) {
28+
const tempPrices = [...prices];
29+
30+
for (const [from, to, price] of flights) {
31+
if (prices[from] === MAX_INT) continue;
32+
33+
const newPrice = prices[from] + price;
34+
if (newPrice < tempPrices[to]) {
35+
tempPrices[to] = newPrice;
36+
}
37+
}
38+
39+
prices = tempPrices;
40+
}
41+
42+
return prices[dst] === MAX_INT ? -1 : prices[dst];
43+
};

0 commit comments

Comments
 (0)