From b907b58d852542c68cdccf7f78bd47662f6f1573 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 28 Aug 2024 00:20:12 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB1514.=20Path=20with=20Maxim?= =?UTF-8?q?um=20Probability=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/path-with-maximum-probability.java | 57 +++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 java/path-with-maximum-probability.java diff --git a/java/path-with-maximum-probability.java b/java/path-with-maximum-probability.java new file mode 100644 index 0000000..40ab9a5 --- /dev/null +++ b/java/path-with-maximum-probability.java @@ -0,0 +1,57 @@ +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; + +class Solution { + private record Edge(int v, double p) {} + + private static Map> makeGraph(int[][] edges, double[] p) { + Map> graph = new HashMap<>(); + + for (int i = 0; i < edges.length; ++i) { + var u = edges[i][0]; + var v = edges[i][1]; + var prob = p[i]; + + graph.computeIfAbsent(u, k -> new ArrayList<>()).add(new Edge(v, prob)); + graph.computeIfAbsent(v, k -> new ArrayList<>()).add(new Edge(u, prob)); + } + + return graph; + } + + private record Entry(double probability, int u) {} + + public double maxProbability( + int n, int[][] edges, double[] succProb, int startNode, int endNode) { + var graph = makeGraph(edges, succProb); + var maxProb = new double[n]; + + PriorityQueue q = + new PriorityQueue<>(Comparator.comparingDouble(Entry::probability).reversed()); + + maxProb[startNode] = 1; + q.add(new Entry(maxProb[startNode], startNode)); + + while (!q.isEmpty()) { + var candidate = q.poll(); + if (candidate.u() == endNode) { + return candidate.probability(); + } + + for (var edge : graph.getOrDefault(candidate.u(), new ArrayList<>())) { + var possibleProbability = candidate.probability() * edge.p(); + + if (possibleProbability > maxProb[edge.v()]) { + maxProb[edge.v()] = possibleProbability; + q.add(new Entry(maxProb[edge.v()], edge.v())); + } + } + } + + return 0; + } +}