Problem Description
Given an undirected weighted graph where each edge has an associated success probability, find the path from a given start node to an end node that maximizes the product of success probabilities along the path. If no such path exists, return 0.
Key Insights
- The problem can be modeled as a graph traversal where the "distance" is defined in terms of cumulative probability (i.e., product of probabilities).
- Instead of summing edge weights (like in a standard shortest path problem), multiply probabilities.
- Dijkstra's algorithm can be adapted to maximize the product by using a max-heap (priority queue) to always extend the path with the highest probability so far.
- An alternative trick is to transform the multiplication problem into an addition problem by using logarithms, but here a direct multiplication approach with proper priority update is more natural.
- Maintain an array holding the best probability reached for each node to avoid unnecessary processing.
Space and Time Complexity
Time Complexity: O(E log V), where E is the number of edges and V is the number of vertices. Space Complexity: O(V + E) for the graph representation and auxiliary data structures.
Solution
We use a modified Dijkstra's algorithm:
- Build an adjacency list representation of the graph.
- Use a max-heap (priority queue) where each element is a pair (current probability, node). The heap always gives the node with the highest probability path computed so far.
- Initialize the probability of reaching the start node as 1 and 0 for all other nodes.
- While the heap is not empty, pop the node with the highest probability. If it is the end node, return its probability.
- For each neighbor, compute the new probability by multiplying the current probability with the probability of the edge connecting to that neighbor. If this new probability is higher than the best known probability for the neighbor, update it and push the neighbor into the heap.
- If the end node is never reached, return 0.