简体   繁体   中英

Wrong output in finding the maximum sum of adjacent digits in a pyramid/triangle

I solving Problem 18 on Project Euler and have written the code for it as below:

v = '''75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23'''.strip().split('\n')


last_ind = 0
max_sum = 75
for row in v[1:]:
    row = row.split(' ')
    num1 = int(row[last_ind])
    num2 = int(row[last_ind+1])
    if num1 > num2:
        max_sum+=num1
    else:
        max_sum+=num2
        last_ind = last_ind+1
        
print(max_sum)    

I got the ANSWER AS 1064 but it's written 1074 everywhere. Can someone please suggest me what I might be doing wrong. By calculating every row by hands, I get 1064 . What is wrong here?

You are assuming that the optimal path will always move down via the child with the greatest value, but this is not true. A child with a lesser value may open up a possibility (at lower layers) to find a much greater value, which more than compensates for the temporary less optimal value.

So your algorithm, in its first iteration will go from 75 to the 95 on the second row. But this turns out to be the wrong choice. You'll have to come up with a better algorithm. You will find inspiration in other Q&A about this particular challenge, like this one .

Here you see the optimal path:

path
95
17 47
18 35 10 10
20 04 47 65 47 65
19 01 23 03 34 03 34
88 02 77 07 63 67 07 63 67
99 65 04 06 16 70 92 06 16 70 92
41 41 26 56 40 80 70 33 40 80 70 33
41 48 72 33 47 37 16 94 29 37 16 94 29
53 71 44 65 25 43 52 97 51 14 52 97 51 14
70 11 33 28 77 73 17 39 68 17 57 39 68 17 57
91 71 52 38 17 14 91 43 50 27 29 48 50 27 29 48
63 66 04 68 89 53 67 30 16 69 87 40 31 16 69 87 40 31
04 62 98 27 23 09 70 98 73 38 53 60 04 23 38 53 60 04 23

Imagine you were on the row just before the bottom row, call it row l . Now for each number m on row l , ask (1) which of the (one or) two choices would be optimal to choose next? (2) what would the sum now look like at m if we added that optimal choice?

Now ask the same questions for the row just above l .

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