Leetcode 1514: Path with Maximum Probability

grid47
grid47
Exploring patterns and algorithms
Jun 8, 2024 8 min read

You are given an undirected, weighted graph of n nodes, represented by an edge list, where each edge connects two nodes with a given success probability. Given two nodes, start and end, find the path with the maximum probability of success to go from start to end.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n`, an edge list `edges`, an array `succProb` of success probabilities for each edge, and two integers `start` and `end`, representing the nodes to traverse from and to.
Example: n = 4, edges = [[0,1],[1,2],[0,2],[2,3]], succProb = [0.9, 0.8, 0.5, 0.7], start = 0, end = 3
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
Output: Return the maximum probability of success of the path from `start` to `end`.
Example: 0.31500
Constraints:
• The answer must be accurate within a relative or absolute error of (10^{-5}).
Goal: The goal is to find the path from `start` to `end` with the highest probability. This can be done using a modified Dijkstra's algorithm, where instead of finding the shortest path, we maximize the product of probabilities.
Steps:
• Step 1: Build a graph representation where each edge has a success probability.
• Step 2: Use a priority queue to perform a modified Dijkstra's algorithm, where at each step, you explore the node with the maximum success probability.
• Step 3: Update the probability of reaching each neighboring node and continue until you reach the `end` node.
Goal: The graph is undirected, and there is at most one edge between each pair of nodes.
Steps:
• The number of nodes `n` can be as large as 10^4, and the number of edges can be as large as 2 * 10^4.
• The success probability for each edge is between 0 and 1 (inclusive).
Assumptions:
• The graph is connected, meaning there is at least one path from `start` to `end` unless otherwise stated.
Input: n = 4, edges = [[0,1],[1,2],[0,2],[2,3]], succProb = [0.9, 0.8, 0.5, 0.7], start = 0, end = 3
Explanation: The problem can be visualized as finding the best route from `0` to `3` by maximizing the product of success probabilities. The highest probability path is through `0 -> 1 -> 2 -> 3`, yielding a success probability of 0.504.

Input: n = 3, edges = [[0,1],[1,2]], succProb = [0.5, 0.5], start = 0, end = 2
Explanation: In this case, the only available path is `0 -> 1 -> 2`, and the success probability is `0.5 * 0.5 = 0.25`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus