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.
37 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 a great candidate for a technique called dynamic programming. We’ll solve it using a bottom-up approach: starting from the second-last row, for each number in the row, we add the larger of the two possible numbers in the row below.

For this problem, we’re going to use python code:

“`python
# Open the file and read it into a list of lists.
with open(“triangle.txt”, ‘r’) as f:
triangle = [[int(num) for num in line.split()] for line in f]

# We start from the second-to-last row.
for i in range(len(triangle) – 2, -1, -1):
for j in range(len(triangle[i])):
# For each number, we add the maximum of the two possible numbers
# in the row below.
triangle[i][j] += max(triangle[i+1][j], triangle[i+1][j+1])

# Print the top of the triangle, which now contains the maximum total.
print(triangle[0][0])
“`

What’s happening is, for each number in a row, starting from the bottom, we’re choosing the maximum path that can be taken from that position. We’re doing this for each row up to the top. By the time we get to the top, we’re left with the maximum total path one can take from the top to the bottom.

This algorithm runs with a time complexity of O(n^2), which is feasible even for a 100-row triangle, compared to the brute force method which runs with a time complexity of O(2^n).

More Answers:
Odd Period Square Roots
Convergents of $e$
Diophantine Equation

Error 403 The request cannot be completed because you have exceeded your quota. : quotaExceeded

Share:

Recent Posts