We have given numbers in form of triangle, by starting at the top of the triangle and moving to adjacent numbers on the row below, find the maximum total from top to bottom.
Input : 3 7 4 2 4 6 8 5 9 3 Output : 23 Explanation : 3 + 7 + 4 + 9 = 23 Input : 8 -4 4 2 2 6 1 1 1 1 Output : 19 Explanation : 8 + 4 + 6 + 1 = 19
We can go through the brute force by checking every possible path but that is much time taking so we should try to solve this problem with the help of dynamic programming which reduces the time complexity.
If we should left shift every element and put 0 at each empty position to make it a regular matrix, then our problem looks like minimum cost path.
So, after converting our input triangle elements into a regular matrix we should apply the dynamic programmic concept to find the maximum path sum.
Applying, DP in bottom-up manner we should solve our problem as:
3 7 4 2 4 6 8 5 9 3 Step 1 : 3 0 0 0 7 4 0 0 2 4 6 0 8 5 9 3 Step 2 : 3 0 0 0 7 4 0 0 10 13 15 0 Step 3 : 3 0 0 0 20 19 0 0 Step 4: 23 0 0 0 output : 23
This article is contributed by Shivam Pradhan (anuj_charm). 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum sum of a path in a Right Number Triangle
- Maximum path sum in an Inverted triangle | SET 2
- Minimum Sum Path in a Triangle
- Minimum length of the shortest path of a triangle
- Maximum path sum for each position with jumps under divisibility condition
- Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
- Maximum sum path in a matrix from top to bottom
- Maximum path sum in the given arrays with at most K jumps
- Maximum sum path in a matrix from top to bottom and back
- Paths from entry to exit in matrix and maximum path sum
- Find maximum path sum in a 2D matrix when exactly two left moves are allowed
- Maximum sum path in a matrix from top-left to bottom-right
- Maximum sum path in a Matrix
- Maximum number of 2x2 squares that can be fit inside a right isosceles triangle
- Maximum height when coins are arranged in a triangle
- Maximum area of triangle having different vertex colors
- Maximum number of squares that can fit in a right angle isosceles triangle
- Maximum Perimeter Triangle from array
- Maximum count of Equilateral Triangles that can be formed within given Equilateral Triangle
- Program to print Sum Triangle for a given array