Does there exist a way an efficient method to find the longest path in a DAG among all possible paths? I know how to solve this in $$$O(V*(V+E))$$$ by considering each vertex as the source, and then using topo sort, and iterating over the vertices in that order and update the distances accordingly. Any suggestions/help would be appreciated or maybe we can prove there doesn't exist a faster method. Thanks!
Auto comment: topic has been updated by peoplePleaser (previous revision, new revision, compare).
Auto comment: topic has been updated by peoplePleaser (previous revision, new revision, compare).
The algorithm you described should be $$$O(V+E)$$$, because you can just relax each edge once in your topo-sort order.
It's $$$O(V+E)$$$ if we fix the source vertex, right? but we need to find the longest path over all possible paths.
Just initialize all vertices to have value 0 instead of -INF; alternatively, make a super-source that connects to all vertices.
Thanks, I thought of this solution. But how to handle the case when all weights are negative? We will always end up with a value of zero, right?
You can store longest non-empty path, in which case you relax $$$val[v] = \max(val[v], \max(val[u], 0) + e)$$$
Thanks got it!
My bad! I am such a fool, if all weights are negative, the answer is the largest (least negative) weight edge.