Similar Problems

Similar Problems not available

Maximum Path Quality Of A Graph - Leetcode Solution

Companies:

LeetCode:  Maximum Path Quality Of A Graph Leetcode Solution

Difficulty: Hard

Topics: backtracking array graph  

Problem Statement:

You are given a directed graph. The graph is represented as an adjacency matrix Adj of size n x n, where each element Adj[i][j] represents the quality of the directed edge from node i to node j. The quality of a path is defined to be the minimum quality of the edges in that path. The path doesn't need to start or end at the root or leaf node, but the path must go from one node to another in the graph. You need to find the maximum quality of any path in the graph.

Solution:

To solve this problem, we need to find the maximum quality of any path in the graph. Since the quality of a path is defined to be the minimum quality of the edges in that path, we need to find the minimum quality of any path from one node to another node. For this, we can use the Floyd Warshall algorithm, which finds the shortest path between all pairs of nodes in the graph.

Let's first initialize a 2D array "dist" of size n x n, where dist[i][j] represents the minimum quality of a path from node i to node j. We can initialize this array with the adjacency matrix Adj.

for i in range(n): for j in range(n): dist[i][j] = Adj[i][j]

Now, we can apply the Floyd Warshall algorithm on this "dist" array to find the minimum quality of any path from one node to another node. The algorithm works as follows:

for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], max(dist[i][k], dist[k][j]))

In the above algorithm, we first loop through all the nodes in the graph (represented by k). For each node k, we loop through all the pairs of nodes (represented by i and j). For each pair of nodes (i, j), we check if the minimum quality of the path from i to j can be improved by going through node k. If it can be improved, we update the dist[i][j] value accordingly.

Finally, we can loop through the "dist" array and find the maximum quality of any path in the graph.

max_quality = float('-inf') for i in range(n): for j in range(n): max_quality = max(max_quality, dist[i][j])

Return the max_quality as the result.

Time Complexity:

The time complexity of the Floyd Warshall algorithm is O(n^3), as we need to loop through all the nodes and pairs of nodes in the graph. Therefore, the overall time complexity of the solution is O(n^3).

Space Complexity:

The space complexity of the solution is O(n^2), as we are using a 2D array of size n x n to store the minimum quality of paths between all pairs of nodes.

Maximum Path Quality Of A Graph Solution Code

1