## Maximum Sum Path

### July 22, 2014

We represent a triangle as a list of lists of its rows; for instance, here are the sample triangle and the triangle from Project Euler 18:

```(define sample   '((3)     (7 4)     (2 4 6)     (8 5 9 3)))```

``` ```

```(define input18   '((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)))```

This is a dynamic programming problem, where lower-level sub-solutions are combined into higher-level sub-solutions until the final solution is reached at the highest level. Consider the sample triangle. If your path reaches the 2 on the third row of the triangle, you will certainly move left to the 8 on the fourth row. If your path reaches the 4 on the third row of the triangle, you will certainly move right to the 9 on the fourth row. And if your path reaches the 6 on the third row of the triangle, you will certainly move left to the 9 on the fourth row. Thus, the sample four-row triangle has the same solution as the three-row triangle shown below:

```    3   7  4 10 13 15```

Then apply the process moving up the tree until you reach the top row. Here is that idea reduced to code:

```(define (max-sum tri)   (define (but-last xs) (reverse (cdr (reverse xs))))   (define (step xs ys)     (map + ys (map max (cdr xs) (but-last xs))))   (let loop ((tri (reverse tri)))     (if (null? (cdr tri)) (caar tri)       (loop (cons (step (car tri) (cadr tri)) (cddr tri))))))```

The `step` internal function calculates the pair-wise maximums of the last row in the inner `map`, then adds them to the next-to-last row in the outer `map`. The `loop` runs over the rows of the triangle in reverse order. reporting the accumulated sum at the top. The `but-last` function returns a list minus its last element. Here are two examples:

```> (max-sum sample) 23 > (max-sum input18) 1074```

Calculation of the path follows the same algorithm, but saves the path instead of the sum at each step:

```(define (max-sum-path tri)   (define (sum xs) (apply + xs))   (define (step last next-to-last)     (let loop ((last last) (next-to-last next-to-last) (out (list)))       (if (null? next-to-last) (reverse out)         (loop (cdr last) (cdr next-to-last)               (if (< (sum (cadr last)) (sum (car last)))                   (cons (cons (car next-to-last) (car last)) out)                   (cons (cons (car next-to-last) (cadr last)) out))))))   (define (fix-last-row tri)     (cons (map list (car tri)) (cdr tri)))   (let loop ((tri (fix-last-row (reverse tri))))     (if (null? (cdr tri)) (caar tri)       (loop (cons (step (car tri) (cadr tri)) (cddr tri))))))```

That looks more complicated than it really is. In its first argument, each `step` receives a list-of-lists of selected path elements instead of a list of their sums, so it has to calculate and compare the sums, then combine the new path element with the winning list-of-lists. The `fix-last-row` function makes each element of the last row of the triangle into a singleton list so that its type is list-of-lists. Here are two examples:

```> (max-sum-path sample) (3 7 4 9) > (max-sum-path input18) (75 64 82 87 82 75 73 28 83 32 91 78 58 73 93)```

Notice that the very first branch goes to a smaller item, 64 compared to 95, because the path sum is larger even though the current item is smaller.

You can run the program at http://programmingpraxis.codepad.org/r70fRj7X.

Pages: 1 2

### 4 Responses to “Maximum Sum Path”

1. Paul said

In Python.

```import StringIO
DATA = """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"""

def bottom_up(data):
while len(data) > 1:
bottom = data.pop()
data[-1][:] = [t + max(bottom[i:i+2]) for i, t in enumerate(data[-1])]
return data

def bottom_up_path(data):
data[-1][:] = [(t, [t]) for t in data[-1]]
while len(data) > 1:
bottom = data.pop()
for i, t in enumerate(data[-1]):
m = max(bottom[i:i+2])
data[-1][i] = (t + m, [t] + m)
return data

data = [[int(x) for x in line.split()] for line in StringIO.StringIO(DATA)]
print bottom_up_path(data)
# (1074, [75, 64, 82, 87, 82, 75, 73, 28, 83, 32, 91, 78, 58, 73, 93])
```
2. matthew said

In C++: read data from stdin to an stl::vector, check it’s triangular and compute what the row size is. Loop over vector filling in maximum subtree sizes, then we can retrieve the path fairly easily by scanning the data again from the top (no need to keep track of paths as we fill in table):

```#include <iostream>
#include <vector>
#include <math.h>
#include <assert.h>
using namespace std;
// 2A = N(N+1) => N^2+N-2A = 0
// a = 1, b = 1, c = -2A
// N = (sqrt(1+8A)-1)/2
int main()
{
vector<int> a;
{
int n;
while(cin >> n) {
a.push_back(n);
}
}
int A = a.size();;
int N = (sqrt(1+8*A)-1)/2; // IEEE754 sqrt needed!
assert(A == N*(N+1)/2);    // Check the input is sane
{
int q = A-N-1; // The table position we are filling in.
for (int n = N-1; n > 0; n--) { // The row widths
for (int i = n; i > 0; i--,q--) { // Go across the row
a[q] += max(a[q+n],a[q+n+1]);
}
}
}
{
int p = 0;    // current index in path
for (int n = 1; n < N; n++) {
int t = a[p]; // current value
p += n+(a[p+n+1] > a[p+n]);
cout << t-a[p] << " ";
}
cout << a[p] << "\n";
}
}
```
```\$ ./maxsumpath <<EOF
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
EOF
75 64 82 87 82 75 73 28 83 32 91 78 58 73 93
```
3. My Scala solution can be found here.

4. svenningsson said

``````module MaximumSumPath where

data Tree a = Node a (Tree a) (Tree a) | Leaf

maxSum = maxSum' 0
maxSum' p Leaf = p
maxSum' p (Node i l r) = max (maxSum' (p+i) l) (maxSum' (p+i) r)

data Choice = L | R deriving Show

maxSumPath = (s,reverse path)
where (s,path) = maxSumPath' (0,[])
maxSumPath' p Leaf = p
maxSumPath' (s,p) (Node i l r) = maxPath (maxSumPath' (s+i,L:p) l)
(maxSumPath' (s+i,R:p) r)
where maxPath p1@(s1,_) p2@(s2,_) | s1 > s2 = p1
| otherwise = p2``````