|
| 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