MediumArrayGraphHeap (Priority Queue)Shortest Path

Path with Maximum Probability

LeetCode
1 approach, code in all languages

You are given an undirected weighted graph of `n` nodes labeled `0` to `n - 1`. Each edge is described by `edges[i] = [a, b]` together with a success probability `succProb[i]`, the chance of successfully traversing that edge.

Given a `start` node and an `end` node, return the maximum probability of successfully travelling from `start` to `end` along some path. The probability of a path is the product of the success probabilities of its edges.

If no path connects `start` and `end`, return `0`. Answers within `1e-5` of the true value are accepted.

Example 1

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

Output: 0.25000

Going 0 -> 1 -> 2 gives 0.5 * 0.5 = 0.25, which beats the direct edge 0 -> 2 at 0.2.

Example 2

Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2

Output: 0.00000

There is no edge that connects node 2 to the rest of the graph, so end is unreachable and the probability is 0.

Constraints

  • 2 <= n <= 10^4
  • 0 <= start, end < n
  • start != end
  • 0 <= a, b < n
  • a != b
  • 0 <= succProb.length == edges.length <= 2 * 10^4
  • 0 <= succProb[i] <= 1
  • There is at most one edge between any two nodes.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now