It is not even that I am clever to have seen the solution works for both problem, it is stated in the problem description which reads
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt, a 15K text file containing a triangle with one-hundred rows.
NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)
However, I thought I would write a short post on it just because otherwise I feel I have a hole in the series. So in Problem 18 I described a solution based on dynamic programming which is the thing we need to use here.
I tried the brute force solution, but I gave up after 10 minutes believing that the twenty billion years in the problem description is probably right after all.
When using the dynamic programming solution we get a solution in 9ms including file access and what have you.
The largest sum through the triangle is: 7273 Solution took 9 ms
The image used in this post is attributed to Norm Walsh who kindly shared it under the creative commons license.