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 = 27.
Now I have to find the maximum total from top to bottom in given 100 rows triangle.
I was thinking about which data structure should I use so that problem will get solved efficiently.
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
itojiffjis one row lower and immediately left or right ofi.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:
To make this work, you will need to weight the
lengthof the path to be the size of the target node (since all paths include the source, this is fine).