![]() |
VOOZH | about |
Given a right triangle of numbers, find the largest of the sum of numbers that appear on the paths starting from the top towards the base, so that on each path the next number is located directly below or below and one place to the right.
Examples :
Input : 1 1 2 4 1 2 2 3 1 1 Output : 9 Explanation : 1 + 1 + 4 + 3 Input : 2 4 1 1 2 7 Output : 10 Explanation : 2 + 1 + 7
Recursion
The idea is to find the largest sum ending at every cell of the last row and return a maximum of these sums. We can recursively compute these sums by recursively considering the above two cells.
6
Complexity Analysis:
Dynamic Programming - Top-Down Approach
Since there are overlapping subproblems, we use dynamic programming to find the maximum sum ending at a particular cell of the last row.
Below is the implementation of the above idea.
6
Complexity Analysis:
Dynamic Programming: Bottom-Up Approach
Since there are overlapping subproblems, we use dynamic programming to find the maximum sum ending at a particular cell of the last row. Below is the implementation of the above idea.
6
Complexity Analysis:
Space Optimization(Without changing the input matrix)
We don't need a matrix of m*n size. It will store all the results.
We just need the triangle row minimum of the immediate bottom row
So using this approach we can optimize the space from O(m*n) to O(n).
The approach remains the same as that of Method 3.
6
Complexity Analysis:
Space Optimization (Changing the input matrix)
6
Complexity Analysis: