## Monday, February 1, 2010

### Project Euler #67: Maximum path sum II

Here is the question:

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 5
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 2^(99) altogether! If you could check one trillion (10^(12)) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

A clever algorithm gives the answer in $$O(log(n))$$ time.

Consider this smaller problem:

   1
2 3
4 5 6


Once you arrive at element 2, you will only ever want to move to number 5, and never 4. Thus, the triangle can be reduced to this:

   1
7 3
5 6


Similarly, when you arrive at 3, you will only ever want to move to 6, so this is the new reduction:

   1
7 9


So lastly, when you reach element 1, you will only ever want to move to 9, giving max sum to be 10.

This is the strategy employed to solve this problem, and here is a solution in Scala:

import scala.io.Source
import scala.Math._

val data = Source.fromFile("problem-00067.txt")
.getLines
.toList
.map(_.trim.split(" ").map(_.toLong))
.toArray

for (i <- data.length - 2 to 0 by -1;
j <- 0 until data(i).length) {
val left = data(i + 1)(j)
val right = data(i + 1)(j + 1)
data(i)(j) += left max right
}

val result = data(0)(0)
println(result)


Credit goes to Jessica Rhee for this solution.