# Maximum sum of a path in a Right Number Triangle

• Difficulty Level : Easy
• Last Updated : 24 May, 2022

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```

Method 1: 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.

## C++

 `// C++ program for``// Recursion implementation of``// Min Sum Path in a Triangle``#include ``using` `namespace` `std;` `// Util function to find minimum sum for a path``int` `helper(vector>& tri, ``int` `i, ``int` `j){``    ``// Base Case ``    ``if``(i == tri.size() ){``      ``return` `0 ;``    ``}``  ` `    ``int` `mx ;``    ``// Add current to the maximum  of the next paths``    ``mx = tri[i][j] + max(helper(tri, i+1,j), helper(tri,i+1, j+1)) ;``    ``//return maximum``    ``return` `mx ;``}`  `int` `maxSumPath(vector>& tri) {``    ``return` `helper(tri, 0, 0) ;``}` `/* Driver program to test above functions */``int` `main()``{``    ``vector > tri{ { 1 },``                            ``{ 2, 1 },``                            ``{ 3, 3, 2 } };``    ``cout << maxSumPath(tri);``    ``return` `0;``}`

## Java

 `// Java program for``// Recursion implementation of``// Min Sum Path in a Triangle``import` `java.io.*;` `class` `GFG``{` `  ``// Util function to find minimum sum for a path``  ``public` `static` `int` `helper(``int` `tri[][], ``int` `i, ``int` `j)``  ``{` `    ``// Base Case``    ``if` `(i == tri.length) {``      ``return` `0``;``    ``}` `    ``int` `mx;``    ` `    ``// Add current to the maximum  of the next paths``    ``mx = tri[i][j]``      ``+ Math.max(helper(tri, i + ``1``, j),``                 ``helper(tri, i + ``1``, j + ``1``));``    ` `    ``// return maximum``    ``return` `mx;``  ``}` `  ``public` `static` `int` `maxSumPath(``int` `tri[][])``  ``{``    ``return` `helper(tri, ``0``, ``0``);``  ``}` `  ``/* Driver program to test above functions */``  ``public` `static` `void` `main(String[] args)``  ``{``    ``int` `tri[][] = { { ``1` `}, { ``2``, ``1` `}, { ``3``, ``3``, ``2` `} };``    ``System.out.print(maxSumPath(tri));``  ``}``}` `// This code is contributed by Rohit Pradhan`

Output

`6`

Complexity Analysis:

• Time Complexity: O(2N*N) where N = number of rows and M = number of columns
• Auxiliary Space: O(N)

Method 2: 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.

## C++

 `// C++ program for Dynamic``// Programming implementation of``// Min Sum Path in a Triangle``#include ``using` `namespace` `std;` `// Util function to find minimum sum for a path``int` `helper(vector>& tri, ``int` `i, ``int` `j, vector>& dp){``    ``// Base Case ``    ``if``(i == tri.size() ){``      ``return` `0 ;``    ``}``  ` `   ``// To avoid solving overlapping subproblem``   ``if``(dp[i][j] != -1){``     ``return` `dp[i][j] ;``   ``}``  `  `    ``// Add current to the minimum  of the next paths``    ``// and store it in dp matrix``    ``return` `dp[i][j] = tri[i][j] + max(helper(tri, i+1,j, dp), helper(tri,i+1, j+1, dp)) ;``    ` `    ` `}`  `int` `maxSumPath(vector>& tri) {``    ``int` `n = tri.size() ;``    ``// Initializating of dp matrix``    ``vector> dp(n, vector<``int``>(n, -1) ) ;``    ``// calling helper function``    ``return` `helper(tri, 0, 0, dp) ;``}` `/* Driver program to test above functions */``int` `main()``{``    ``vector > tri{ { 1 },``                            ``{ 2, 1 },``                            ``{ 3, 3, 2 } };``    ``cout << maxSumPath(tri);``    ``return` `0;``}`

Output

`6`

Complexity Analysis:

• Time Complexity: O(N*M) where N = number of rows and M = number of columns
• Auxiliary Space: O(N2)

Method 3: 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.

## C++

 `// C++ program for Dynamic``// Programming implementation of``// Min Sum Path in a Triangle``#include ``using` `namespace` `std;` `// Util function to find minimum sum for a path``int` `helper(vector>& tri, ``int` `i, ``int` `j, vector>& dp){``    ``int` `n = tri.size() ;``      ``// loop for bottom-up calculation``     ``for``(``int` `j = 0; j < n; j++ ){``            ``dp[n-1][j] = tri[n-1][j] ;``        ``}``        ` `        ``for``(``int` `i = n-2; i >= 0; i--){``            ``for``(``int` `j = i; j >= 0; j-- ){``                ``dp[i][j] = tri[i][j] + max(dp[i+1][j] , dp[i+1][j+1]) ;``            ``}``        ``}``        ` `        ``return` `dp ;``    ` `    ` `}`  `int` `maxSumPath(vector>& tri) {``    ``int` `n = tri.size() ;``    ``// Initializating of dp matrix``    ``vector> dp(n, vector<``int``>(n, -1) ) ;``    ``// calling helper function``    ``return` `helper(tri, 0, 0, dp) ;``}` `/* Driver program to test above functions */``int` `main()``{``    ``vector > tri{ { 1 },``                            ``{ 2, 1 },``                            ``{ 3, 3, 2 } };``    ``cout << maxSumPath(tri);``    ``return` `0;``}`

Output

`6`

Complexity Analysis:

• Time Complexity: O(m*n) where m = no of rows and n = no of columns
• Space Complexity: O(n2)

Method 4: 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).

Approach remains the same as that of Method 3.

## C++

 `// C++ program for Dynamic``// Programming implementation of``// Min Sum Path in a Triangle``#include ``using` `namespace` `std;` `// Util function to find minimum sum for a path``int` `helper(vector>& tri, ``int` `i, ``int` `j, vector>& dp){``    ``int` `n = tri.size() ;``    ``vector<``int``> front(n, -1) , curr(n, -1) ;` `    ``for``(``int` `j = 0; j < n; j++ ){``      ``front[j] = tri[n-1][j] ;``    ``}` `    ``for``(``int` `i = n-2; i >= 0; i--){``      ``for``(``int` `j = i; j >= 0; j-- ){``        ``curr[j] = tri[i][j] + max(front[j] , front[j+1]) ;``      ``}``      ``front = curr ;``    ``}` `    ``return` `front ;``    ` `}`  `int` `maxSumPath(vector>& tri) {``    ``int` `n = tri.size() ;``    ``// Initializating of dp matrix``    ``vector> dp(n, vector<``int``>(n, -1) ) ;``    ``// calling helper function``    ``return` `helper(tri, 0, 0, dp) ;``}` `/* Driver program to test above functions */``int` `main()``{``    ``vector > tri{ { 1 },``                            ``{ 2, 1 },``                            ``{ 3, 3, 2 } };``    ``cout << maxSumPath(tri);``    ``return` `0;``}`

Output

`6`

Complexity Analysis:

• Time Complexity: O(m*n) where m = no of rows and n = no of columns
• Space Complexity: O(n)

Method 5: Space Optimization (Changing the input matrix)

## C++

 `// C++ program to print maximum sum``// in a right triangle of numbers``#include``using` `namespace` `std;` `// function to find maximum sum path``int` `maxSum(``int` `tri[], ``int` `n)``{``    ``// Adding the element of row 1 to both the``    ``// elements of row 2 to reduce a step from``    ``// the loop``    ``if` `(n > 1)``        ``tri = tri + tri;``        ``tri = tri + tri;` `    ``// Traverse remaining rows``    ``for``(``int` `i = 2; i < n; i++) {``        ``tri[i] = tri[i] + tri[i-1];``        ``tri[i][i] = tri[i][i] + tri[i-1][i-1];` `        ``//Loop to traverse columns``        ``for` `(``int` `j = 1; j < i; j++){` `            ``// Checking the two conditions,``            ``// directly below and below right.``            ``// Considering the greater one``            ` `            ``// tri[i] would store the possible``            ``// combinations of sum of the paths``            ``if` `(tri[i][j] + tri[i-1][j-1] >=``                            ``tri[i][j] + tri[i-1][j])``                ` `                ``tri[i][j] = tri[i][j] + tri[i-1][j-1];``            ``else``                ``tri[i][j] = tri[i][j]+tri[i-1][j];``        ``}``    ``}``    ` `    ``// array at n-1 index (tri[i]) stores``    ``// all possible adding combination, finding``    ``// the maximum one out of them``    ``int` `max=tri[n-1];``    ` `    ``for``(``int` `i=1;i

## Java

 `// Java program to print maximum sum``// in a right triangle of numbers``class` `GFG``{``    ` `    ``// function to find maximum sum path``    ``static` `int` `maxSum(``int` `tri[][], ``int` `n)``    ``{``        ` `        ``// Adding the element of row 1 to both the``        ``// elements of row 2 to reduce a step from``        ``// the loop``        ``if` `(n > ``1``)``            ``tri[``1``][``1``] = tri[``1``][``1``] + tri[``0``][``0``];``            ``tri[``1``][``0``] = tri[``1``][``0``] + tri[``0``][``0``];``    ` `        ``// Traverse remaining rows``        ``for``(``int` `i = ``2``; i < n; i++) {``            ``tri[i][``0``] = tri[i][``0``] + tri[i-``1``][``0``];``            ``tri[i][i] = tri[i][i] + tri[i-``1``][i-``1``];``    ` `            ``//Loop to traverse columns``            ``for` `(``int` `j = ``1``; j < i; j++){``    ` `                ``// Checking the two conditions,``                ``// directly below and below right.``                ``// Considering the greater one``                ` `                ``// tri[i] would store the possible``                ``// combinations of sum of the paths``                ``if` `(tri[i][j] + tri[i-``1``][j-``1``] >=``                           ``tri[i][j] + tri[i-``1``][j])``                    ` `                    ``tri[i][j] = tri[i][j]``                                  ``+ tri[i-``1``][j-``1``];``                    ` `                ``else``                    ``tri[i][j] = tri[i][j]``                                    ``+ tri[i-``1``][j];``            ``}``        ``}``        ` `        ``// array at n-1 index (tri[i]) stores``        ``// all possible adding combination,``        ``// finding the maximum one out of them``        ``int` `max = tri[n-``1``][``0``];``        ` `        ``for``(``int` `i = ``1``; i < n; i++)``        ``{``            ``if``(max < tri[n-``1``][i])``                ``max = tri[n-``1``][i];``        ``}``        ` `        ``return` `max;``    ``}``        ` `    ``// Driver code``    ``public` `static` `void` `main (String[] args)``    ``{``        ``int` `tri[][] = {{``1``}, {``2``,``1``}, {``3``,``3``,``2``}};``        ` `        ``System.out.println(maxSum(tri, ``3``));``    ``}``}` `// This code is contributed by Anant Agarwal.`

## Python3

 `# Python program to print maximum sum``# in a right triangle of numbers.` `# tri[][] is a 2D array that stores the``# triangle, n is number of lines or rows.``def` `maxSum(tri, n):` `    ``# Adding the element of row 1 to both the``    ``# elements of row 2 to reduce a step from``    ``# the loop``    ``if` `n > ``1``:``        ``tri[``1``][``1``] ``=` `tri[``1``][``1``]``+``tri[``0``][``0``]``        ``tri[``1``][``0``] ``=` `tri[``1``][``0``]``+``tri[``0``][``0``]` `    ``# Traverse remaining rows``    ``for` `i ``in` `range``(``2``, n):``        ``tri[i][``0``] ``=` `tri[i][``0``] ``+` `tri[i``-``1``][``0``]``        ``tri[i][i] ``=` `tri[i][i] ``+` `tri[i``-``1``][i``-``1``]` `        ``# Loop to traverse columns``        ``for` `j ``in` `range``(``1``, i):` `            ``# Checking the two conditions, directly below``            ``# and below right. Considering the greater one` `            ``# tri[i] would store the possible combinations``            ``# of sum of the paths``            ``if` `tri[i][j]``+``tri[i``-``1``][j``-``1``] >``=` `tri[i][j]``+``tri[i``-``1``][j]:``                ``tri[i][j] ``=` `tri[i][j] ``+` `tri[i``-``1``][j``-``1``]``            ``else``:``                ``tri[i][j] ``=` `tri[i][j]``+``tri[i``-``1``][j]` `    ``# array at n-1 index (tri[i]) stores all possible``    ``# adding combination, finding the maximum one``    ``# out of them``    ``print` `(``max``(tri[n``-``1``]))` `# driver program``tri ``=` `[[``1``], [``2``,``1``], [``3``,``3``,``2``]]``maxSum(tri, ``3``)`

## C#

 `// C# program to print``// maximum sum in a right``// triangle of numbers``using` `System;` `class` `GFG``{``    ` `    ``// function to find``    ``// maximum sum path``    ``static` `int` `maxSum(``int` `[,]tri,``                      ``int` `n)``    ``{``        ` `        ``// Adding the element of row 1``        ``// to both the elements of row 2``        ``// to reduce a step from the loop``        ``if` `(n > 1)``            ``tri[1, 1] = tri[1, 1] +``                        ``tri[0, 0];``            ``tri[1, 0] = tri[1, 0] +``                        ``tri[0, 0];``    ` `        ``// Traverse remaining rows``        ``for``(``int` `i = 2; i < n; i++)``        ``{``            ``tri[i, 0] = tri[i, 0] +``                        ``tri[i - 1, 0];``            ``tri[i, i] = tri[i, i] +``                        ``tri[i - 1, i - 1];``     ` `            ``//Loop to traverse columns``            ``for` `(``int` `j = 1; j < i; j++)``            ``{``    ` `                ``// Checking the two conditions,``                ``// directly below and below right.``                ``// Considering the greater one``                ` `                ``// tri[i] would store the possible``                ``// combinations of sum of the paths``                ``if` `(tri[i, j] + tri[i - 1, j - 1] >=``                    ``tri[i, j] + tri[i - 1, j])``                ` `                    ``tri[i, j] = tri[i, j] +``                                ``tri[i - 1, j - 1];``                    ` `                ``else``                    ``tri[i, j] = tri[i, j] +``                                ``tri[i - 1, j];``            ``}``        ``}``        ` `        ``// array at n-1 index (tri[i])``        ``// stores all possible adding``        ``// combination, finding the``        ``// maximum one out of them``        ``int` `max = tri[n - 1, 0];``        ` `        ``for``(``int` `i = 1; i < n; i++)``        ``{``            ``if``(max < tri[n - 1, i])``                ``max = tri[n - 1, i];``        ``}``        ` `        ``return` `max;``    ``}``        ` `// Driver Code``public` `static` `void` `Main ()``{``    ` `        ``int` `[,]tri = {{1,0,0},``                      ``{2,1,0},``                      ``{3,3,2}};``        ` `        ``Console.Write(maxSum(tri, 3));``}``}` `// This code is contributed by ajit.`

## PHP

 ` 1)``        ``\$tri`` = ``\$tri`` + ``\$tri``;``        ``\$tri`` = ``\$tri`` + ``\$tri``;` `    ``// Traverse remaining rows``    ``for``(``\$i` `= 2; ``\$i` `< ``\$n``; ``\$i``++)``    ``{``        ``\$tri``[``\$i``] = ``\$tri``[``\$i``] +``                      ``\$tri``[``\$i` `- 1];``        ``\$tri``[``\$i``][``\$i``] = ``\$tri``[``\$i``][``\$i``] +``                       ``\$tri``[``\$i` `- 1][``\$i` `- 1];` `        ``//Loop to traverse columns``        ``for` `(``\$j` `= 1; ``\$j` `< ``\$i``; ``\$j``++)``        ``{` `            ``// Checking the two conditions,``            ``// directly below and below right.``            ``// Considering the greater one``            ` `            ``// tri[i] would store the possible``            ``// combinations of sum of the paths``            ``if` `(``\$tri``[``\$i``][``\$j``] + ``\$tri``[``\$i` `- 1][``\$j` `- 1] >=``                 ``\$tri``[``\$i``][``\$j``] + ``\$tri``[``\$i` `- 1][``\$j``])``                ` `                ``\$tri``[``\$i``][``\$j``] = ``\$tri``[``\$i``][``\$j``] +``                               ``\$tri``[``\$i` `- 1][``\$j` `- 1];``            ``else``                ``\$tri``[``\$i``][``\$j``] = ``\$tri``[``\$i``][``\$j``] +``                               ``\$tri``[``\$i` `- 1][``\$j``];``        ``}``    ``}``    ` `    ``// array at n-1 index (tri[i])``    ``// stores all possible adding``    ``// combination, finding the``    ``// maximum one out of them``    ` `    ``\$max` `= ``\$tri``[``\$n` `- 1];``    ` `    ``for``(``\$i` `= 1; ``\$i` `< ``\$n``; ``\$i``++)``    ``{``        ``if``(``\$max` `< ``\$tri``[``\$n` `- 1][``\$i``])``            ``\$max` `= ``\$tri``[``\$n` `- 1][``\$i``];``    ``}``    ` `    ``return` `\$max``;``}` `// Driver Code``\$tri` `= ``array``(``array``(1),``             ``array``(2,1),``             ``array``(3,3,2));` `echo` `maxSum(``\$tri``, 3);` `// This code is contributed by ajit``?>`

## Javascript

 ``

Output

`6`

Complexity Analysis:

• Time Complexity: O(m*n) where m = no of rows and n = no of columns
• Space Complexity: O(1)

This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.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.

My Personal Notes arrow_drop_up