Problem Link - Sums in a Triangle
Problem Statement:
Given an integer N
, we have a triangle of numbers where the first line contains one number, the second line contains two numbers, the third line contains three numbers, and so on, up to N
lines. The goal is to compute the largest sum of numbers along paths starting from the top of the triangle to the base.
Approach:
The key idea of this solution is to use dynamic programming to find the maximum path sum from the top of the triangle to the base. We maintain a 2D array, DP, where DP[i][j] represents the maximum sum that can be obtained when reaching the element in the i-th
row and j-th
column.
Here’s how the approach works:
-
Filling the Triangle: For each number in the triangle represented by
A[i][j]
:-
If it’s the first number in a row (i.e., j=1), the maximum sum to reach this number is simply the number itself plus the sum from directly above it:
DP[i][j]=A[i][j]+DP[i−1][j]
. -
For all other numbers in that row, we calculate the maximum sum possible by taking the maximum of the two possible paths leading to it:
DP[i][j]=A[i][j]+max(DP[i−1][j−1],DP[i−1][j])
This way, for each number in the current row, we consider the best path that could have led there.
-
-
Finding the Maximum Path Sum: Once we have filled in the DP table, the answer will be the maximum value in the last row of DP. This gives the largest sum of all possible paths from the top to the base of the triangle.
Time Complexity:
- The time complexity of the solution is
O(N^2)
because we need to fill in a triangle of sizeN
.
Space Complexity:
- The space complexity is also
O(N^2)
due to the storage required for the DP array.