oneby7

Advanced Graphs Weighted shortest paths

481. Path with Maximum Probability

Medium

You are given an undirected graph with n nodes, labelled from 0 to n - 1. Each edges[i] = [a, b] joins nodes a and b, and you can cross it in either direction. Crossing it succeeds with probability succProb[i].

A path from start_node to end_node succeeds only if every edge on it succeeds, so its probability is the product of the probabilities of its edges. Return the largest probability of any path from start_node to end_node. If no path joins them, return 0. If start_node and end_node are the same node, return 1.

An answer within 10-5 of the expected one is accepted.

Example 1

0.50.80.90.90.50.30start_node1234end_node

Input: n = 5 edges = [[0, 1], [1, 4], [0, 2], [2, 3], [3, 4], [0, 4]] succProb = [0.5, 0.8, 0.9, 0.9, 0.5, 0.3] start_node = 0 end_node = 4

Output: 0.405

Explanation: The path 0 → 2 → 3 → 4 succeeds with probability 0.9 × 0.9 × 0.5 = 0.405. That beats 0 → 1 → 4, with 0.5 × 0.8 = 0.4, and the direct edge, with 0.3.

Example 2

0.70.90start_node123end_node

Input: n = 4 edges = [[0, 1], [2, 3]] succProb = [0.7, 0.9] start_node = 0 end_node = 3

Output: 0

Explanation: No path joins node 0 to node 3, so the answer is 0.

Example 3

0.250.5012start_node, end_node

Input: n = 3 edges = [[1, 0], [1, 2]] succProb = [0.25, 0.5] start_node = 2 end_node = 2

Output: 1

Explanation: We start at the end node, so we cross no edge, and the answer is 1.

Check your understanding

Work out the answer for this input before you write any code.

n = 3 edges = [[0, 1], [1, 2], [0, 2]] succProb = [0.5, 0.8, 0.3] start_node = 0 end_node = 2

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 105
  • edges[i] = [a, b], with 0 ≤ a, b < n
  • succProb.length == edges.length
  • 0 ≤ succProb[i] ≤ 1
  • 0 ≤ start_node, end_node < n
  • Two edges can join the same two nodes, and an edge can join a node to itself.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.