Largest Sum of a Path in a Triangle
Given a file consisting a pascals-like triangle of integers separated by spaces, return the sum of the path with the largest sum, as well as the final column index in the triangle. A path can only iterate down to the next level below to its child. Each parent shares 2 adjacent children in the level below. e.g. in the second row parent 2 shares children 2 and 3 and parent 3 shares shares children 3 and 4.
Note: integers can be >9
and <0
.
Visually:
Actually:
output:
Explanation: The sum of the max path is 25, and the column it end with is @index 3, which contains integer 8
. The reason why we want to return the column index is because we can use it as information to backtrace back up the tree and return the actual path. Observe:
This is done by taking the number at said column and then selecting the maximum of one of its two parents.
The Idea:
We can structure the information into a binary tree then do a path traversal to the leaf node, but in my opinion this would be a lot more difficult to parse, we can just use BFS iteratively.
First I parse the information into an indexable 2 dimensional vector. Then I begin the BFS procedure using an object of type
Node
that will carries information about the particular index.cur_sum
is preferably important because it allows be to dynamically refer back to the previous sum. This works because the associative property of addition tells us that2 + 3 + 5 = 3 + 2 + 5
, i.e. permutations don't matter. Therow
andcol
information is used to refer to the next index in the 2d array. I know for a fact that it will be in the next row down, same col and an additional column forward.
Last updated