![]() |
VOOZH | about |
Given a graph with n vertex and m-directed edges. One lowercase letter is assigned to each vertex. The value of the path is the number of the most frequently occurring letters in the path. The task is to find a path whose value is the largest.
Example:
Input: n = 5, m = 4, node_value = "abaca", edges[] = {1 2}, {1 3}, {3 4}, {4, 5}
Output: 3Input: n = 6, m = 6, node_value = "xzyabc", edges[] = {1, 2}, {3, 1}, {2, 3}, {5, 4}, {4, 3}, {6, 4}
Output: -1
Approach:
The idea is to use dynamic programming to avoid redundant traversal of nodes. Use a 2-D array 'dp', where dp[i][j] represents the maximum count of character 'j' when reaching node i. 'i' ranges from 1 to N, and 'j' from 0 to 25 (representing 'a' to 'z'). Use topological sorting to calculate dp values, ensuring that nodes with edges to node 'i' are visited first. If a cycle is detected in the graph, the function returns -1 to indicate an infinitely large result due to repetitive traversal of the cycle.
Step-by-step approach:
Below is the implementation of the above approach:
Maximum path value: 3
Time Complexity: O(N), Where 'N' is the number of nodes in the given graph.
Auxiliary Space: O(N)