SDE & MLE Prep

1514. Path with Maximum Probability

Problem

In an undirected graph, traversing edge edges[i] succeeds with probability succProb[i]. Return the highest probability of successfully going from start_node to end_node, or 0 if there's no path.

Example: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2 → 0.25

Constraints: n ≤ 10⁴; up to 2·10⁴ edges.

Dijkstra with a max-heap on probability: probabilities only shrink along a path (multiplying by ≤ 1), so the greedy "best first" argument still holds.

Complexity: O(E log V).

class Solution:
    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
        g = defaultdict(list)
        for (a, b), p in zip(edges, succProb):
            g[a].append((b, p))
            g[b].append((a, p))
        best = [0.0] * n
        best[start_node] = 1.0
        pq = [(-1.0, start_node)]
        while pq:
            p, u = heappop(pq)
            p = -p
            if u == end_node:
                return p
            if p < best[u]:
                continue
            for v, w in g[u]:
                if p * w > best[v]:
                    best[v] = p * w
                    heappush(pq, (-best[v], v))
        return 0.0