DAG algorithm

int[] longestPath(List[] graph, int src) {
  List order = topologicalSort(graph);
  int[] dp = new int[graph.length];
  Arrays.fill(dp, Integer.MIN_VALUE);
  dp[src] = 0;
  for (int u : order) {
    if (dp[u] == Integer.MIN_VALUE) continue;
    for (int[] edge : graph[u]) {
      int v = edge[0], w = edge[1];
      dp[v] = Math.max(dp[v], dp[u] + w);
    }
  }
  return dp;
}
Advertisement

Complexity

O(V+E). Same as topo sort + linear scan.

Advertisement

General graph

NP-hard. Even unweighted: reduces to Hamiltonian path.

Special structures

Trees: DFS with two-longest tracking. Cactus graphs (disjoint cycles): polynomial via reductions.