Project Euler - Problem 18, Problem 67 - Maximum path sum

#Dynamic Programming #Project Euler #Sport Programming

Table of Contents

Its been quite sometime since I did some coding. Last Sunday, one of the best friends of mine (Clement Lloyd) asked me if I can solve Project Euler's Problem 18. The problem name is Maximum path sum. Finally I got some time today and it is a simple Dynamic Programming Problem. The basic idea is to, keep on adding two adjacent elements of each row with the corresponding element in the previous row and keep the maximum of them. For example,
\\

 8
1 2

\\ The maximum of 8+1 and 8+2 would be 10 and 10 would take 8's place. So we keep on doing this till we reach the top. For the sample input
\\

3
  7 4
 2 4 6
8 5 9 3

\\ After first Iteration,
\\

3
   7  4
 10 13 15

\\ After second Iteration,
\\

3
  20 19

\\ After third Iteration,
\\

23

\\ Here is the solution which I used
\\

 1import sys
 2sys.stdin  = open ("Input.txt")
 3sys.stdout = open ("Output.txt", "w")
 4Array = []
 5for line in sys.stdin: Array.append (map (int, line.split()))
 6Array.reverse()
 7temp_array = [0] * (len(Array) + 1)
 8for Row in Array:
 9 for i in xrange (len(Row)):
10  temp_array[i] = Row[i] + max (temp_array[i], temp_array[i + 1])
11print max (temp_array)

\\ This solution will solve Project Euler's Problem 67 as well.
\\ \\ \\