VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-cost-path-from-source-node-to-destination-node-via-at-most-k-intermediate-nodes/

⇱ Maximum cost path from source node to destination node via at most K intermediate nodes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum cost path from source node to destination node via at most K intermediate nodes

Last Updated : 23 Jul, 2025

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:

👁 Image


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:

  • Initialize the variable, say ans, to store the maximum distance between the source and the destination node having at most K intermediates nodes.
  • Initialize an adjacency list of the graph using the edges.
  • Initialize an empty queue and push the source vertex into it. Initialize a variable, say lvl, to store the number of nodes present in between src and dst.
  • While the queue is not empty and lvl is less than K + 2 perform the following steps:
    • Store the size of the queue in a variable, say S.
    • Iterate over the range[1, S] and perform the following steps:
      • Pop the front element of the queue and store it in a variable, say T.
      • If T is the dst vertex, then update the value of ans as the maximum of ans and the current distance T.second.
      • Traverse through all the neighbors of the current popped node and check if the distance of its neighbor is greater than the current distance or not. If found to be true, then push it in the queue and update its distance.
    • Increase the value of lvl by 1.
  • After completing the above steps, print the value of ans as the resultant maximum distance.

Below is the implementation of the above approach:


Output
500

Time Complexity: O(N + E)
Auxiliary Space: O(N)

Alternate approach: Modification of Bellman Ford algorithm after modifying the weights

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


Output
500

Time Complexity: O(E*k) where E is the number of edges
Auxiliary Space: O(n)

Comment
Article Tags: