Skip to content

Commit 58e6ba0

Browse files
committed
Add solution #1514
1 parent 4d25268 commit 58e6ba0

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,340 LeetCode solutions in JavaScript
1+
# 1,341 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1157,6 +1157,7 @@
11571157
1510|[Stone Game IV](./solutions/1510-stone-game-iv.js)|Hard|
11581158
1512|[Number of Good Pairs](./solutions/1512-number-of-good-pairs.js)|Easy|
11591159
1513|[Number of Substrings With Only 1s](./solutions/1513-number-of-substrings-with-only-1s.js)|Medium|
1160+
1514|[Path with Maximum Probability](./solutions/1514-path-with-maximum-probability.js)|Medium|
11601161
1519|[Number of Nodes in the Sub-Tree With the Same Label](./solutions/1519-number-of-nodes-in-the-sub-tree-with-the-same-label.js)|Medium|
11611162
1524|[Number of Sub-arrays With Odd Sum](./solutions/1524-number-of-sub-arrays-with-odd-sum.js)|Medium|
11621163
1528|[Shuffle String](./solutions/1528-shuffle-string.js)|Easy|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 1514. Path with Maximum Probability
3+
* https://leetcode.com/problems/path-with-maximum-probability/
4+
* Difficulty: Medium
5+
*
6+
* You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list
7+
* where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability
8+
* of success of traversing that edge succProb[i].
9+
*
10+
* Given two nodes start and end, find the path with the maximum probability of success to go from
11+
* start to end and return its success probability.
12+
*
13+
* If there is no path from start to end, return 0. Your answer will be accepted if it differs from
14+
* the correct answer by at most 1e-5.
15+
*/
16+
17+
/**
18+
* @param {number} n
19+
* @param {number[][]} edges
20+
* @param {number[]} succProb
21+
* @param {number} startNode
22+
* @param {number} endNode
23+
* @return {number}
24+
*/
25+
var maxProbability = function(n, edges, succProb, startNode, endNode) {
26+
const maxProbs = new Array(n).fill(0);
27+
maxProbs[startNode] = 1;
28+
29+
const graph = Array.from({ length: n }, () => []);
30+
edges.forEach(([a, b], i) => {
31+
graph[a].push([b, succProb[i]]);
32+
graph[b].push([a, succProb[i]]);
33+
});
34+
35+
const queue = [startNode];
36+
while (queue.length) {
37+
const current = queue.shift();
38+
for (const [next, prob] of graph[current]) {
39+
const newProb = maxProbs[current] * prob;
40+
if (newProb > maxProbs[next]) {
41+
maxProbs[next] = newProb;
42+
queue.push(next);
43+
}
44+
}
45+
}
46+
47+
return maxProbs[endNode];
48+
};

0 commit comments

Comments
 (0)