I have this as a homework and i need to do it in python.
Problem:
The Maximum Route is defined as the maximum total by traversing from the tip of the triangle to its base. Here the maximum route is (3+7+4+9) 23.
3
7 4
2 4 6
8 5 9 3
Now, given a certain triangle, my task is to find the Maximum Route for it.
Not sure how to do it….
We can solve this problem using backtracking. To do that for each element of the triangle in any given row, we have to determine the maximum of sum of the current element and the three connected neighbors in the next row, or
First try to find a way to determine
connected_neighbors of col in rowfor an elem in position (row,col), connected neighbor in row = next would be
[next[col-1],next[col],next[col+1]]providedcol - 1 >=0andcol+1 < len(next). Here is am sample implementationThis will return the index of the connected neighbors.
now we can write
backtrack_elem = max([elem + i for i in connected_neighbors of col in row])asand if we iterate the triangle rowwise and curr is any given row then and i is the ith col index of the row then we can write
now we have to iterate the triangle reading the current and the next row together. This can be done as
and then we use enumerate to generate a tuple of index and the elem itself
Clubbing then together we have
But the above operation is destructive and we have to create a copy of the original triangle and work on it
So we have to use the
deepcopymoduleand rewrite out traverse as
We end up with another triangle where every elem gives the highest route cost possible. To get the actual route, we have to use the original triangle and calculate backward
so for an elem at index
[row,col], the highest route cost is route[row][col]. If it follows the max route, then the next elem should be a connected neighbor and the route cost should be route[row][col] – orig[row][col]. If we iterate row wise we can write asand we should loop downwards starting from the peak element. Thus we have
Lets take a bit complex example, as yours is too trivial to solve
Generating the Route
and finally we calculate the route
To Test our triangle we have
Reading a comment by jamylak, I realized this problem is similar to Euler 18 but the difference is the representation. The problem in Euler 18 considers a pyramid where as the problem in this question is of a right angle triangle. As you can read my reply to his comment I explained the reason why the results would be different. Nevertheless, this problem can be easily ported to work with Euler 18. Here is the port