Skip to content

1857. Largest Color Value in a Directed Graph #1730

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to determine the largest color value in a directed graph, considering possible cycles. If the graph contains a cycle, we return -1. Otherwise, we compute the maximum color value using dynamic programming combined with topological sorting.

Approach

  1. Cycle Detection and Topological Sort: Use Kahn's algorithm to perform a topological sort. If the number of processed nodes is less than the total nodes, the graph contains a cycle, and we return -1.
  2. Dynamic Programming (DP): For each node processed in topological order, maintain a DP array where dp[u][c] represents the maximum count of color c in any path ending at node u.
  3. Reverse Adjacency List: Track predecessors for each node to effi…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz May 26, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim May 26, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants