Skip to content

Instantly share code, notes, and snippets.

@kaipakartik
Created January 11, 2014 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaipakartik/8372820 to your computer and use it in GitHub Desktop.
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.
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