Problem #67 is the first instance of a problem that is just a more computationally intensive version of an earlier problem. The question reads:
Project Euler Problem 67: Maximum path sum II 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. 3 7 4 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 (right click and 'Save Link/Target As...'), 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 299 altogether! 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)
This problem is exactly the same as Problem #18, but with a much larger triangle. Thus, the dynamic approach that was presented in my blog post for Problem #18 is mandatory for solving this problem. Here is my solution:
Solution #1: Dynamic Approach (Copy/Paste from #18)
We simply store the maximum path sum from each cell to the bottom and work our way up the triangle as we did in Problem #18. Here is an implementation of this approach in Python 2.7:
'''
Author: Walker Kroubalkian
Dynamic Approach to Project Euler Problem #67
'''
import time
f = open("PE67Triangle.txt","r")
if(f.mode == "r"):
contents = f.readlines()
realContents = []
for x in contents:
realContents.append(map(int,x.split()))
else:
raise ValueError("Cannot read from file")
def projectEulerProblemSixtySeven(triangle):
rows = len(triangle)
currentRow = triangle[rows-1]
c = (rows-2)
while(c>=0):
temp = []
for i in range(c+1):
temp.append(triangle[c][i] + max(currentRow[i],currentRow[i+1]))
currentRow = temp
c-=1
return currentRow[0]
start = time.time()
print projectEulerProblemSixtySeven(realContents)
print ("--- %s seconds ---" % (time.time()-start))
'''
Prints
7273
--- 0.00120997428894 seconds ---
for input of triangle = given triangle
'''
And with that, we are officially 2/3 of the way to solving 100 questions on Project Euler. This is a great example of the powers of Dynamic programming. Rather than brute forcing 2^100 paths, we only need to run through the 5050 cells in the triangle once, and the program runs in just over a millisecond in Python 2.7.
Thanks for reading! See you tomorrow.

