Skip to content

Commit cd54717

Browse files
authored
Create 1514-path-with-maximum-probability.kt
1 parent c963573 commit cd54717

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double {
3+
val adj = HashMap<Int, ArrayList<Pair<Int, Double>>>().apply {
4+
for ((i, edge) in edges.withIndex()) {
5+
val (u, v) = edge
6+
this[u] = getOrDefault(u, ArrayList<Pair<Int, Double>>()).apply { add(v to succProb[i]) }
7+
this[v] = getOrDefault(v, ArrayList<Pair<Int, Double>>()).apply { add(u to succProb[i]) }
8+
}
9+
}
10+
11+
val visited = HashSet<Int>()
12+
val minHeap = PriorityQueue<Pair<Int, Double>>{ a, b ->
13+
if (a.second < b.second) 1 else -1
14+
}
15+
16+
with (minHeap) {
17+
add(start to 1.0)
18+
19+
while (isNotEmpty()) {
20+
val (node, currCost) = poll()
21+
visited.add(node)
22+
23+
if (node == end) return currCost
24+
25+
adj[node]?.forEach {
26+
if (it.first !in visited) {
27+
add(it.first to currCost * it.second)
28+
}
29+
}
30+
}
31+
}
32+
33+
return 0.0
34+
}
35+
}

0 commit comments

Comments
 (0)