Given a triangle of this shape
3
7 4
2 4 6
8 5 9 3
Taking a route from top to bottom, moving to adjacent numbers in the row below, and adding the numbers on the path - what is the maximum sum we can get?
Rather than going from top to bottom, we can go from bottom to top. If we get to “4” in the third row, we should chose 9 - because that will maximise the sum regardles of the path that led us to the 4.
So we collapse the larger triangle from bottom to top.
Having figured this out, two steps remain. Store the triangle in some datastructure. Write a function that take the two last rows, and collapse them into a new row with the maximum possible result. Update the triangle, and continue until only the top row is left. Theres your answer.
Let us write at function that collapses two rows into one:
collapse <- function(a, b ){
output <- numeric()
for(i in 1:length(a)){
output[i] <- max(a[i]+b[i], a[i]+b[i+1])
}
output
}
Import the data into something we can work with:
triangle <- str_split(triangle, "\\n") %>% unlist() %>%
str_split(" ") %>%
lapply(as.numeric)
Throw everything together:
lowest <- length(triangle)
while(lowest > 2){
lowest <- length(triangle)
triangle[[lowest - 1]] <- collapse(triangle[[lowest-1]], triangle[[lowest]])
triangle[[lowest]] <- NULL
}
answer <- unlist(triangle)