Created
January 11, 2014 16:12
-
-
Save kaipakartik/8372820 to your computer and use it in GitHub Desktop.
Maximum path sum I and 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
a = [] | |
def getTriangleFromFile(): | |
f = open("triangle.txt") | |
for line in f: | |
b = [int(x) for x in line.split()] | |
a.append(b) | |
maxPaths = dict() | |
def getMaxPathLength(x,y): | |
if y < 0: | |
return 0 | |
if x >= len(a[-1]): | |
return 0 | |
if (x,y) in maxPaths: | |
return maxPaths[x,y] | |
maxPaths[x,y] = a[x][y] + max(getMaxPathLength(x+1, y +1), getMaxPathLength(x+1,y)) | |
return maxPaths[x,y] | |
getTriangleFromFile() | |
print getMaxPathLength(0,0) | |
print maxPaths |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment