Skip to main content
Back to problems
#1514
Medium Algorithms

Path with maximum probability

Array Graph Theory Heap (Priority Queue) Shortest Path
65.5% acceptance
Mar 1, 2026
3878
110
You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i]. Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability. If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
use std::collections::BinaryHeap;

impl Solution {
  pub fn max_probability(
    n: i32,
    edges: Vec<Vec<i32>>,
    succ_prob: Vec<f64>,
    start_node: i32,
    end_node: i32,
  ) -> f64 {
    let n = n as usize;
    let s = start_node as usize;
    let e = end_node as usize;
    let mut adj: Vec<Vec<(usize, f64)>> = vec![vec![]; n];
    for (i, edge) in edges.iter().enumerate() {
      let (a, b) = (edge[0] as usize, edge[1] as usize);
      adj[a].push((b, succ_prob[i]));
      adj[b].push((a, succ_prob[i]));
    }
    let mut prob = vec![0.0f64; n];
    prob[s] = 1.0;
    // Max-heap using to_bits(): for non-negative f64, bit ordering == numeric ordering
    let mut heap: BinaryHeap<(u64, usize)> = BinaryHeap::new();
    heap.push((1.0f64.to_bits(), s));
    while let Some((p_bits, u)) = heap.pop() {
      let p = f64::from_bits(p_bits);
      if u == e { return p; }
      if p < prob[u] { continue; }
      for &(v, w) in &adj[u] {
        let np = prob[u] * w;
        if np > prob[v] {
          prob[v] = np;
          heap.push((np.to_bits(), v));
        }
      }
    }
    prob[e]
  }
}