Maximum path sum in a triangle. - GeeksforGeeks

07 Apr, 2022
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. Examples :  
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 
 
Method1: 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. 
Implementation of Recursive Approach:
C++
Python3
Javascript
// C++ program for// Recursive implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 //  Function for finding maximum sumint maxPathSum(int tri[][N], int i, int j, int row, int col){     if(j == col ){         return 0;     }        if(i == row-1 ){         return tri[i][j] ;     }        return tri[i][j] + max(maxPathSum(tri, i+1, j, row, col),                            maxPathSum(tri, i+1, j+1, row, col)) ;} /* Driver program to test above functions */int main(){   int tri[N][N] = {  {1, 0, 0},                      {4, 8, 0},                      {1, 5, 3} };   cout << maxPathSum(tri, 0, 0, 3, 3);   return 0;}
# Python program for# Recursive implementation of# Max sum problem in a triangleN = 3 #  Function for finding maximum sumdef maxPathSum(tri, i, j, row, col):     if(j == col ):         return 0        if(i == row-1 ):         return tri[i][j]        return tri[i][j] + max(maxPathSum(tri, i+1, j, row, col),                            maxPathSum(tri, i+1, j+1, row, col)) # Driver program to test above functionstri = [  [1, 0, 0],[4, 8, 0],[1, 5, 3] ]print(maxPathSum(tri, 0, 0, 3, 3)) # This code is contributed by shinjanpatra
<script> // JavaScript program for// Recursive implementation of// Max sum problem in a triangle const N = 3 //  Function for finding maximum sumfunction maxPathSum(tri, i, j, row, col){     if(j == col ){         return 0;     }        if(i == row-1 ){         return tri[i][j] ;     }        return tri[i][j] + Math.max(maxPathSum(tri, i+1, j, row, col),                            maxPathSum(tri, i+1, j+1, row, col)) ;} /* Driver program to test above functions */let tri = [  [1, 0, 0],[4, 8, 0],[1, 5, 3] ];document.write(maxPathSum(tri, 0, 0, 3, 3)); // This code is contributed by shinjanpatra </script>
14
Complexity Analysis:
Time Complexity: O(2N*N)
Space Complexity:  O(N)
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. 
Method 2: DP Top-Down
Since there are overlapping subproblems, we can avoid the repeated work done in method 1 by storing the min-cost path calculated so far using top-down approach
C++
// C++ program for Dynamic// Programming implementation (Top-Down) of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 //  Function for finding maximum sumint maxPathSum(int tri[][N], int i, int j, int row, int col, vector<vector<int>> &dp){     if(j == col ){         return 0;     }        if(i == row-1 ){         return tri[i][j] ;     }        if(dp[i][j] != -1){         return -1 ;     }        return dp[i][j] = tri[i][j] + max(maxPathSum(tri, i+1, j, row, col, dp),                                   maxPathSum(tri, i+1, j+1, row, col, dp)) ;} /* Driver program to test above functions */int main(){   int tri[N][N] = {  {1, 0, 0},                      {4, 8, 0},                      {1, 5, 3} };   vector<vector<int>> dp(N, vector<int>(N, -1) ) ;   cout << maxPathSum(tri, 0, 0, N, N, dp);   return 0;}
14
Complexity Analysis:
Time Complexity:  O(m*n) where m = no of rows and n = no of columns
Space Complexity: O(n2)
Method 3: DP(Bottom – UP)
Since there are overlapping subproblems, we can avoid the repeated work done in method 1 by storing the min-cost path calculated so far using bottom-up approach thus reducing stack space
C++
// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 //  Function for finding maximum sumint maxPathSum(int tri[][N], int n, vector<vector<int>> &dp){     // 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[0][0] ;      } /* Driver program to test above functions */int main(){   int tri[N][N] = {  {1, 0, 0},                      {4, 8, 0},                      {1, 5, 3} };   vector<vector<int>> dp(N, vector<int>(N, -1) ) ;   cout << maxPathSum(tri, N, dp);   return 0;}
14
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 Changning input matrix)
We do not need a 2d matrix we only need a 1d array that stores the minimum of the immediate next column  and thus we can reducing space
C++
// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 //  Function for finding maximum sumint maxPathSum(int tri[][N], int n, vector<vector<int>> &dp){        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[0] ;      } /* Driver program to test above functions */int main(){   int tri[N][N] = {  {1, 0, 0},                      {4, 8, 0},                      {1, 5, 3} };   vector<vector<int>> dp(N, vector<int>(N, -1) ) ;   cout << maxPathSum(tri, N, dp);   return 0;}
14
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 input matrix)
 Applying, DP in bottom-up manner we should solve our problem as: Example:  
   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
 
C++
Java
Python3
C#
PHP
Javascript
// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 //  Function for finding maximum sumint maxPathSum(int tri[][N], int m, int n){     // loop for bottom-up calculation     for (int i=m-1; i>=0; i--)     {        for (int j=0; j<=i; j++)        {            // for each element, check both            // elements just below the number            // and below right to the number            // add the maximum of them to it            if (tri[i+1][j] > tri[i+1][j+1])                tri[i][j] += tri[i+1][j];            else                tri[i][j] += tri[i+1][j+1];        }     }      // return the top element     // which stores the maximum sum     return tri[0][0];} /* Driver program to test above functions */int main(){   int tri[N][N] = {  {1, 0, 0},                      {4, 8, 0},                      {1, 5, 3} };   cout << maxPathSum(tri, 2, 2);   return 0;}
// Java Program for Dynamic// Programming implementation of// Max sum problem in a triangleimport java.io.*; class GFG {             static int N = 3;         // Function for finding maximum sum    static int maxPathSum(int tri[][], int m, int n)    {        // loop for bottom-up calculation        for (int i = m - 1; i >= 0; i--)        {            for (int j = 0; j <= i; j++)            {                // for each element, check both                // elements just below the number                // and below right to the number                // add the maximum of them to it                if (tri[i + 1][j] > tri[i + 1][j + 1])                    tri[i][j] += tri[i + 1][j];                else                    tri[i][j] += tri[i + 1][j + 1];            }        }             // return the top element        // which stores the maximum sum        return tri[0][0];    }         /* Driver program to test above functions */    public static void main (String[] args)    {        int tri[][] = { {1, 0, 0},                        {4, 8, 0},                        {1, 5, 3} };        System.out.println ( maxPathSum(tri, 2, 2));    }} // This code is contributed by vt_m
# Python program for# Dynamic Programming# implementation of Max# sum problem in a# triangle N = 3 # Function for finding maximum sumdef maxPathSum(tri, m, n):     # loop for bottom-up calculation    for i in range(m-1, -1, -1):        for j in range(i+1):             # for each element, check both            # elements just below the number            # and below right to the number            # add the maximum of them to it            if (tri[i+1][j] > tri[i+1][j+1]):                tri[i][j] += tri[i+1][j]            else:                tri[i][j] += tri[i+1][j+1]     # return the top element    # which stores the maximum sum    return tri[0][0] # Driver program to test above function tri = [[1, 0, 0],       [4, 8, 0],       [1, 5, 3]]print(maxPathSum(tri, 2, 2)) # This code is contributed# by Soumen Ghosh.
// C# Program for Dynamic Programming// implementation of Max sum problem// in a triangleusing System; class GFG {         // Function for finding maximum sum    static int maxPathSum(int [,]tri,                          int m, int n)    {        // loop for bottom-up calculation        for (int i = m - 1; i >= 0; i--)        {            for (int j = 0; j <= i; j++)            {                // for each element,                // check both elements                // just below the number                // and below right to                // the number add the                // maximum of them to it                if (tri[i + 1,j] >                       tri[i + 1,j + 1])                    tri[i,j] +=                           tri[i + 1,j];                else                    tri[i,j] +=                       tri[i + 1,j + 1];            }        }             // return the top element        // which stores the maximum sum        return tri[0,0];    }         /* Driver program to test above    functions */    public static void Main ()    {        int [,]tri = { {1, 0, 0},                        {4, 8, 0},                        {1, 5, 3} };                                 Console.Write (             maxPathSum(tri, 2, 2));    }} // This code is contributed by nitin mittal.
<?php// PHP program for Dynamic// Programming implementation of// Max sum problem in a triangle // Function for finding// maximum sumfunction maxPathSum($tri, $m, $n){    // loop for bottom-up    // calculation    for ( $i = $m - 1; $i >= 0; $i--)    {        for ($j = 0; $j <= $i; $j++)        {            // for each element, check            // both elements just below            // the number and below right            // to the number add the maximum            // of them to it            if ($tri[$i + 1][$j] > $tri[$i + 1]                                       [$j + 1])                $tri[$i][$j] += $tri[$i + 1][$j];            else                $tri[$i][$j] += $tri[$i + 1]                                    [$j + 1];        }    }     // return the top element    // which stores the maximum sum    return $tri[0][0];} // Driver Code$tri= array(array(1, 0, 0),            array(4, 8, 0),            array(1, 5, 3));echo maxPathSum($tri, 2, 2); // This code is contributed by ajit?>
<script>// Javascript Program for Dynamic// Programming implementation of// Max sum problem in a triangle    let N = 3;           // Function for finding maximum sum    function maxPathSum(tri, m, n)    {             // loop for bottom-up calculation        for (let i = m - 1; i >= 0; i--)        {            for (let j = 0; j <= i; j++)            {                             // for each element, check both                // elements just below the number                // and below right to the number                // add the maximum of them to it                if (tri[i + 1][j] > tri[i + 1][j + 1])                    tri[i][j] += tri[i + 1][j];                else                    tri[i][j] += tri[i + 1][j + 1];            }        }               // return the top element        // which stores the maximum sum        return tri[0][0];    }         // Driver code       let tri = [[1, 0, 0],                  [4, 8, 0],                  [1, 5, 3]];       document.write( maxPathSum(tri, 2, 2));               // This code is contributed by susmitakundugoaldanga.           </script>
14
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 Shivam Pradhan (anuj_charm). 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. 
jit_t
nitin mittal
susmitakundugoaldanga
prasanna1995
shinjanpatra
triangle
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Sieve of Eratosthenes
Edit Distance | DP-5
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number
Overlapping Subproblems Property in Dynamic Programming | DP-1
Find minimum number of coins that make a given value