Longest path Created 2026-10-25 Updated 2026-11-05
A longest path maximizes path length, either the number of edges or the sum of specified edge weights, under the stated endpoints and simple-path convention. In a general graph, imposing vertex simplicity makes the optimization computationally difficult; a directed acyclic graph admits a direct dynamic programming solution. Allowing arbitrary walks instead requires care with reachable positive cycles. The convention permitting a zero-edge path gives a possible value zero even when all nonempty paths have negative weight.
First the graph is connected: every component has at least vertices, so two components cannot fit. Take a longest path . Every neighbour of either endpoint lies on that path. In the index set define
Their sizes sum to , so they share an index . The edges at that index give the cycle
containing every vertex of the path. The minimum-degree assumption and ensure the resulting cycle is nondegenerate. If it omitted any graph vertex, connectedness would supply an edge from outside it to the cycle. Starting with that outside vertex and then following the cycle without closing it gives a path with vertices, contradicting maximality. Thus the cycle is Hamiltonian. This proves Dirac's theorem in the required case.
A tree is a nonempty connected graph with no graph cycle. A leaf of a tree is a vertex of vertex degree one. As usual in this finite graph theory problem, trees are finite; the assertion would fail for a doubly infinite graph path.
Take a longest path in a tree with at least two vertices. Connectedness gives . If had a neighbour outside this graph path, the path could be extended, contradicting maximal length. If it had a neighbour with , that edge together with the segment would make a graph cycle. Thus its only neighbour is , and it is a leaf of a tree. The same argument at the other end makes a second, distinct leaf of a tree. Hence
Find a topological sorting of the directed acyclic graph. Initialize and for . Process vertices in that order. At a reachable vertex , update each outgoing edge by , and retain a predecessor whenever an improvement is made.
Every path to a vertex ends at an earlier vertex in the topological sorting. Thus, when is processed, all possible final-edge candidates for have already been considered. Induction along the order proves that is the longest path length from , with exactly for unreachable vertices. Signed weights cause no problem because the graph has no directed cycle. The running time is , and predecessor pointers recover a maximizing path.