![]() |
VOOZH | about |
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: 2Input: 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:
Below is the implementation of the above approach:
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.