In Project Euler\'s problem 67 there is a triangle given and it contains 100 rows. For e.g.
5
9 6
4 6 8
0 7 1 5
I.e. 5 + 9 + 6 + 7
You want to store this as a directed acyclic graph. The nodes are the entries of your triangular array, and there is an arrow from i to j iff j is one row lower and immediately left or right of i.
Now you want to find the maximum weight directed path (sum of the vertex weights) in this graph. In general, this problem is NP-complete, however, as templatetypedef points out, there are efficient algorithms for DAGs; here's one:
algorithm dag-longest-path is
input:
Directed acyclic graph G
output:
Length of the longest path
length_to = array with |V(G)| elements of type int with default value 0
for each vertex v in topOrder(G) do
for each edge (v, w) in E(G) do
if length_to[w] <= length_to[v] + weight(G,(v,w)) then
length_to[w] = length_to[v] + weight(G, (v,w))
return max(length_to[v] for v in V(G))
To make this work, you will need to weight the length of the path to be the size of the target node (since all paths include the source, this is fine).