简体   繁体   中英

Path with maximum sum in a triangle

I made a program for finding the max sum among all possible paths in a triangle

EXAMPLE:

       1
      2 1
     1 2 3

Then the max value among all possible paths is 1+2+3=6

My code:

def maxSum(tri, n):
    if n > 1:
         tri[1][1] = tri[1][1]+tri[0][0]
         tri[1][0] = tri[1][0]+tri[0][0]
    for i in range(2, n):
         tri[i][0] = tri[i][0] + tri[i-1][0]
         tri[i][i] = tri[i][i] + tri[i-1][i-1]
    for j in range(1, i):
         if tri[i][j]+tri[i-1][j-1] >= tri[i][j]+tri[i-1][j]:
            tri[i][j] = tri[i][j] + tri[i-1][j-1]
         else:
            tri[i][j] = tri[i][j]+tri[i-1][j]
print max(tri[n-1])


#my list containing the triangle
tri = [[1], [2,1], [1,2,3]]
maxSum(tri, 3)

But my code is printing the output as 5.Anyone please help me to correct my code ?

If I am not wrong ,here is your requirement

For a triangle of 3 , you will have 6 elements and you want to get max path (means select all possible 3 elements combinations and get the combination of 3 numbers where you will give maximum sum. This can be achieved with a simple code

Code

`# declaring list
tri=[[1], [2, 1], [1, 2, 3]]`

#getting all possible 3 elements combinations out of available 6 elements. The below two lines will give list of tuples
import itertools
temptri=list(itertools.product(*tri))

#Converting tuple to list
ftri=[]
for i in temptri:
    ftri.append(list(i))
#getting max sum of the avilable 3 elements combinations
print sum(max(ftri, key=sum))

Example input/output

input
tri=[[1], [2, 5], [1, 2, 3]]
output 
6

input
[[1], [2, 5], [1, 2, 3]]
output
9

input
[[1], [2, 5], [1, 2, 3],[1,2,3,7]]
output
16

You haven't specified what a valid path is and so just like Sandeep Lade, i too have made an assumption: To get the sum of maximum numbers in the triangle:

def maximum(x):
    return max(x)

triangle= [[1], [2, 1], [1, 2, 3],[2,3,4,5]]
#the above can be represented as:
#        1
#      2   1
#     1  2  3
#    2  3  4  5

max_numbers = list(map(maximum,triangle))
print(max_numbers,'====>',sum(max_numbers))

gives you the sum of maximum numbers in the triangle and its scalable for any size of the triangle

You can make code even more concise using lambda functions:

print(sum(list(map(lambda x:max(x),triangle))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM