![]() |
VOOZH | about |
Given a directed weighted graph consisting of N vertices and an array Edges[][], with each row representing two vertices connected by an edge and the weight of that edge, the task is to find the path with the maximum sum of weights from a given source vertex src to a given destination vertex dst, made up of at most K intermediate vertices. If no such path exists, then print -1.
Examples:
Input: N = 3, Edges[][] = {{0, 1, 100}, {1, 2, 100}, {0, 2, 500}}, src = 0, dst = 2, K = 0
Output: 500
Explanation:
Path 0 → 2: The path with maximum weight and at most 0 intermediate nodes is of weight 500.
Approach: The given problem can be solved by using BFS(Breadth-First Search) Traversal. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
500
Time Complexity: O(N + E)
Auxiliary Space: O(N)
If all the weights of the given graph are made negative of the original weights, the path taken to minimize the sum of weights with at most k nodes in middle will give us the path we need. Hence this question is similar to this problem. Below is the code implementation of the problem
500
Time Complexity: O(E*k) where E is the number of edges
Auxiliary Space: O(n)