Path with Maximum Probability

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_node` and `end_node`, find the path with the maximum probability of success to go from `start_node` to `end_node` and return its success probability. If there is no path from `start_node` to `end_node`, return 0.

30:00

Path with Maximum Probability
medium
Free written solution
Topics
Companies

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_node and end_node, find the path with the maximum probability of success to go from start_node to end_node and return its success probability. If there is no path from start_node to end_node, return 0.

Example 1:
Input: {"n":3,"edges":[[0,1],[1,2],[0,2]],"succProb":[0.5,0.5,0.2],"start_node":0,"end_node":2}
Output: 0.25
Constraints:
  • 2≤n≤1042 \leq n \leq 10^4

  • 0≤start_node,end_node<n0 \leq \text{start\_node}, \text{end\_node} < n

  • start_node≠end_node\text{start\_node} \neq \text{end\_node}

  • 0≤a,b<n0 \leq a, b < n

  • a≠ba \neq b

  • 0≤succProb.length==edges.length≤2×1040 \leq \text{succProb.length} == \text{edges.length} \leq 2 \times 10^4

  • 0≤succProb[i]≤10 \leq \text{succProb}[i] \leq 1

  • There is at most one edge between every two nodes.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":3,"edges":[[0,1],[1,2],[0,2]],"succProb":[0.5,0.5,0.2],"start_node":0,"end_node":2}

Every node starts at probability 0 except the start node 0, which starts at 1. Put (1, 0) in a max-heap so the most likely node is always handled next.

route

0 → 2

popped

-

best[2]

0

settled

0/3

0.50.50.2011020
numbers outside = best probability so fargreen = settled

max-heap

0:1
Variables
VariableValue
start_node0
end_node2
edges3
DepthFunction Call
Stack empty
0/7