Space
Open
From Fieldwork
Scales
Archive
This problem is a variation of the Shortest Path Problem. Instead of summing weights to find the minimum distance, we are multiplying probabilities to find the maximum likelihood.
import heapq
from collections import defaultdict
from typing import List
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
# 1. Build the Graph (Adjacency List)
# Since the graph is undirected, we add edges for both directions.
graph = defaultdict(list)
for i, (u, v) in enumerate(edges):
prob = succProb[i]
graph[u].append((v, prob))
graph[v].append((u, prob))
# 2. Initialize Dijkstra's Variables
# Max-Heap stores: (-probability, current_node)
# We start with probability 1.0 at the start_node (stored as -1.0)
pq = [(-1.0, start_node)]
# Array to store the max probability to reach node 'i'
max_prob = [0.0] * n
max_prob[start_node] = 1.0
# 3. Process the Heap
while pq:
cur_p, cur_node = heapq.heappop(pq)
cur_p = -cur_p # Convert back to positive
# If we reached the target, this is guaranteed to be the max probability
# due to the greedy nature of Dijkstra's algorithm.
if cur_node == end_node:
return cur_p
# Optimization: If the current probability is smaller than what we
# have already found for this node, skip processing.
if cur_p < max_prob[cur_node]:
continue
# Explore neighbors
for neighbor, edge_prob in graph[cur_node]:
new_prob = cur_p * edge_prob
# If we found a path with a higher probability, update and push to heap
if new_prob > max_prob[neighbor]:
max_prob[neighbor] = new_prob
heapq.heappush(pq, (-new_prob, neighbor))
# If the queue empties and we never reached end_node
return 0.0Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode