VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-edges-in-the-path/

⇱ Maximum Edges In The Path - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Edges In The Path

Last Updated : 9 Dec, 2023

Given a directed graph with n nodes and m edges. Each edge is assigned a weight. The graph can also be disconnected and there might be multiple edges and self-loops. The task is to choose a path such that the weights of the edges are in strictly increasing order and the path has the maximum possible number of edges(The path can contain the same vertices multiple times). Note:- The edges must be in the order of input

Example:

Input: n = 3, m = 3, inputEdges = {{3, 1, 3}, {1, 2, 1}, {2, 3, 2}}
Output: 2

Input: n = 5, m = 5, inputEdges = {{1, 3, 2}, {3, 2, 3}, {3, 4, 5}, {5, 4, 0}, {4, 5, 8}}
Output: 3

Approach:

The idea is to use a dynamic programming approach by maintaining a vector of maps (edges) where each map corresponds to a node and stores the maximum length of the path ending at that node with a particular weight.

For each input edge, calculates the length of the path ending at the starting node (a) with the given weight (w). It then checks if extending the path to the ending node (b) by including the current edge maintains the strictly increasing order of weights. If so, updates the information in the edges vector accordingly. Also removes conflicting edges in a way that ensures the weights are strictly increasing. The maximum length of the paths ending at different nodes is continuously updated, and the final result is the maximum length among these paths.

Steps:

  • Create a vector of maps to represent the directed graph and store the maximum length of paths ending at each node with a specific weight.
  • Iterate through the given edges, calculating the length of the path ending at the starting node with the given weight.
  • For each edge, check if extending the path to the ending node maintains the strictly increasing order of weights.
  • Update the length information for the ending node with the given weight, and remove conflicting edges in a way that ensures weights are strictly increasing.
  • Continuously update the maximum length of paths ending at different nodes.
  • Print the maximum length of the path, considering the specified conditions.

Below is the implementation of the above approach:


Output
2

Time Complexity: logO(E log N), where E is the number of edges and N is the number of nodes.
Auxiliary Space: O(V+E), where V is the number of vertices and E is the number of edges.

Comment