forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1514-path-with-maximum-probability.ts
More file actions
37 lines (30 loc) · 1000 Bytes
/
1514-path-with-maximum-probability.ts
File metadata and controls
37 lines (30 loc) · 1000 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function maxProbability(
n: number,
edges: number[][],
succProb: number[],
startNode: number,
endNode: number,
): number {
const adjList = new Map(Array.from({ length: n }, (_, i) => [i, []]));
for (let i = 0; i < edges.length; i++) {
const [origin, target] = edges[i];
const prob = succProb[i];
adjList.get(origin).push([target, prob]);
adjList.get(target).push([origin, prob]);
}
const table = new Array(n).fill(0);
table[startNode] = 1;
const heap = new MaxPriorityQueue({ priority: (a) => a[1] });
for (let edge of adjList.get(startNode)) {
heap.enqueue(edge);
}
while (!heap.isEmpty()) {
const { element: maxEdge } = heap.dequeue();
if (table[maxEdge[0]] >= maxEdge[1]) continue;
table[maxEdge[0]] = maxEdge[1];
for (let edge of adjList.get(maxEdge[0])) {
heap.enqueue([edge[0], edge[1] * maxEdge[1]]);
}
}
return table[endNode];
}