Project Euler Solution 67: Maximum path sum II

Project Euler Problem 67: Maximum path sum II is the sequel to Problem 18.

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.

text 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, 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)

We can just the efficient algorithm from Solution 18: Maximum path sum I. We only need to adjust the loading a bit as it now comes from a file. The solution_bottom_up is exactly the same.

def load_triangle() -> list[list[int]]:
    with open("data/p067_triangle.txt") as f:
        data = f.read()
    return [[int(word) for word in line.split()] for line in data.strip().split("\n")]


def solution_bottom_up() -> int:
    triangle = load_triangle()
    for row_i in reversed(range(len(triangle) - 1)):
        row = triangle[row_i]
        for col_i in range(len(row)):
            row[col_i] += max(
                triangle[row_i + 1][col_i], triangle[row_i + 1][col_i + 1]
            )
    return triangle[0][0]

This solves the problem in 2.0 ms. If one already used the efficient algorithm for Problem 18, this is kind of lame.