Given a triangular structure of numbers, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Input : 2 3 7 8 5 6 6 1 9 3 Output : 11 Explanation : 2 + 3 + 5 + 1 = 11 Input : 3 6 4 5 2 7 9 1 8 6 Output : 10 Explanation : 3 + 4 + 2 + 1 = 10
Naive Approach : Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.
There are two ways to reach the solution :
1. Memoization – Starting from the top node, traverse recursively with each node, till the pathsum of that node is calculated. And then store the result in an array. But this will take O(N^2) space to maintain the array.
2. Bottom up – Start from the nodes on the bottom row; the min pathsum for these nodes are the values of the nodes themselves. And after that, minimum pathsum at the ith node of kth row would be the minimum of the pathsum of its two children + the node’s value, i.e.:
memo[k][i] = min( memo[k+1][i], memo[k+1][i+1]) + A[k][i];
Simply set memo as a 1D array, and update it
this will be space efficient also :
For the row k :
memo[i] = min( memo[i], memo[i+1]) + A[k][i];
Below is the implementation of above dynamic programming approach :
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum path sum in a triangle.
- Maximum sum of a path in a Right Number Triangle
- Size of The Subarray With Maximum Sum
- Longest Increasing Subsequence | DP-3
- Minimum number of jumps to reach end
- Nested list in C++ STL
- Program to print half diamond Number-Star pattern
- C++ Program to implement Symbol Table
- Number of quadrilaterals possible from the given points
- Program to find N-th term of the series a, b, b, c, c, c,…….