Solution

ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2019/functional-programming-design-and-analysis-of-algorithms/8/c/ii/solution

Permit every vertex to start a path: initialize for all , then perform the same maximum-relaxation pass in topological sorting order. Equivalently, the recurrence is
The zero option starts a fresh, zero-edge path; the other options extend an optimal path ending at a predecessor. The largest final entry is therefore the longest path length in the graph, allowing a zero-edge path. This takes , which is for the ordinary simple-graph representation.
If at least one edge is required, keep the same prefix values but return instead of . That variant correctly returns a negative optimum when all nonempty paths have negative weight, and reports no nonempty path if the edge set is empty. No all-pairs repetition is needed.

New to topics? Read the docs here!