Skip to content
Related Articles

Related Articles

Maximum path sum in an Inverted triangle | SET 2

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 23 Jun, 2022

Given numbers in form of an Inverted triangle. By starting at the bottom of the triangle and moving to adjacent numbers on the row above, find the maximum total from bottom to top.
Examples: 
 

Input : 1 5 3
         4 8
          1
Output : 14

Input : 8 5 9 3
         2 4 6
          7 4
           3
Output : 23

 

Method 1: Recursion

 In the previous article we saw an approach of the problem where the triangle is non-inverted.
Here also we will use the same approach to find the solution of the problem as discussed in previous article.
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

Implementation of Recursive Approach:

C++




// 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 sum
int maxPathSum(int tri[][N], int i, int j, int row, int col){
     if(j == col ){
         return INT_MIN;
     }
   
     if(i == 0 ){
         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, 5, 3 },
                      { 4, 8, 0 },
                      { 1, 0, 0 } };
   cout << maxPathSum(tri, 2, 0, 2, 2);
   return 0;
}

Output

14

Complexity Analysis:

  • Time Complexity: O(2N*N)
  • Space Complexity:  O(N)

Method 2: DP Top-Down
So, after converting our input triangle elements into a regular matrix we should apply the dynamic programming concept to find the maximum path sum.

C++




// 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 sum
int maxPathSum(int tri[][N], int i, int j, int row, int col, vector<vector<int>> &dp){
     if(j == col ){
         return INT_MIN;
     }
   
     if(i == 0 ){
         return tri[i][j] ;
     }
   
     if(dp[i][j] != -1){
         return dp[i][j] ;
     }
   
     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, 5, 3 },
                      { 4, 8, 0 },
                      { 1, 0, 0 } };
   vector<vector<int>> dp(N, vector<int>(N, -1) ) ;
   cout << maxPathSum(tri, 2, 0, 2, 2, dp);
   return 0;
}

Output

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

Applying, DP in a bottom-up manner we should solve our problem as: 
Example : 
 

8 5 9 3
 2 4 6
  7 4
   3

Step 1 :
8 5 9 3
2 4 6 0
7 4 0 0
3 0 0 0

Step 2 :
8 5 9 3
2 4 6 0
10 7 0 0

Step 3 :
8 5 9 3
12 14 13 0

Step 4:
20 19 23 16

Output : 23

Below is the implementation of the above approach: 
 

C++




// C++ program implementation of
// Max sum problem in a triangle
#include <bits/stdc++.h>
using namespace std;
#define N 3
 
// Function for finding maximum sum
int maxPathSum(int tri[][N])
{
    int ans = 0;
 
    // Loop for bottom-up calculation
    for (int i = N - 2; i >= 0; i--) {
        for (int j = 0; j < N - i; j++) {
 
            // For each element, check both
            // elements just below the number
            // and below left to the number
            // add the maximum of them to it
            if (j - 1 >= 0)
                tri[i][j] += max(tri[i + 1][j],
                                 tri[i + 1][j - 1]);
            else
                tri[i][j] += tri[i + 1][j];
 
            ans = max(ans, tri[i][j]);
        }
    }
 
    // Return the maximum sum
    return ans;
}
 
// Driver Code
int main()
{
    int tri[N][N] = { { 1, 5, 3 },
                      { 4, 8, 0 },
                      { 1, 0, 0 } };
 
    cout << maxPathSum(tri);
 
    return 0;
}

Java




// Java program implementation of
// Max sum problem in a triangle
 
class GFG
{
    static int N = 3;
 
    // Function for finding maximum sum
    static int maxPathSum(int tri[][])
    {
        int ans = 0;
     
        // Loop for bottom-up calculation
        for (int i = N - 2; i >= 0; i--)
        {
            for (int j = 0; j < N - i; j++)
            {
     
                // For each element, check both
                // elements just below the number
                // and below left to the number
                // add the maximum of them to it
                if (j - 1 >= 0)
                    tri[i][j] += Math.max(tri[i + 1][j],
                                    tri[i + 1][j - 1]);
                else
                    tri[i][j] += tri[i + 1][j];
     
                ans = Math.max(ans, tri[i][j]);
            }
        }
     
        // Return the maximum sum
        return ans;
    }
     
    // Driver Code
    public static void main(String []args)
    {
        int tri[][] = { { 1, 5, 3 },
                        { 4, 8, 0 },
                        { 1, 0, 0 } };
     
        System.out.println(maxPathSum(tri));
    }
}
 
// This code is contributed by ihritik

Python3




# Python program implementation of
# Max sum problem in a triangle
 
N = 3
 
# Function for finding maximum sum
def maxPathSum( tri ):
 
    ans = 0;
 
    # Loop for bottom-up calculation
    for i in range(N - 2, -1, -1):
        for j in range(0 , N - i):
 
            # For each element, check both
            # elements just below the number
            # and below left to the number
            # add the maximum of them to it
            if (j - 1 >= 0):
                tri[i][j] += max(tri[i + 1][j],
                                tri[i + 1][j - 1]);
            else:
                tri[i][j] += tri[i + 1][j];
 
            ans = max(ans, tri[i][j]);
     
    # Return the maximum sum
    return ans
     
# Driver Code
     
tri = [ [ 1, 5, 3 ],
        [ 4, 8, 0 ],
        [ 1, 0, 0 ] ]
 
print(maxPathSum(tri))
 
# This code is contributed by ihritik

C#




// C# program implementation of
// Max sum problem in a triangle
using System;
 
class GFG
{
    static int N = 3;
 
    // Function for finding maximum sum
    static int maxPathSum(int [,]tri)
    {
        int ans = 0;
     
        // Loop for bottom-up calculation
        for (int i = N - 2; i >= 0; i--)
        {
            for (int j = 0; j < N - i; j++)
            {
     
                // For each element, check both
                // elements just below the number
                // and below left to the number
                // add the maximum of them to it
                if (j - 1 >= 0)
                    tri[i, j] += Math.Max(tri[i + 1, j],
                                    tri[i + 1, j - 1]);
                else
                    tri[i, j] += tri[i + 1, j];
     
                ans = Math.Max(ans, tri[i, j]);
            }
        }
     
        // Return the maximum sum
        return ans;
    }
     
    // Driver Code
    public static void Main()
    {
        int[,] tri = { { 1, 5, 3 },
                        { 4, 8, 0 },
                        { 1, 0, 0 } };
     
        Console.WriteLine(maxPathSum(tri));
    }
}
 
// This code is contributed by ihritik

PHP




<?php
// PHP program implementation of
// Max sum problem in a triangle
 
$N = 3;
 
// Function for finding maximum sum
function maxPathSum($tri)
{
    global $N;
    $ans = 0;
 
    // Loop for bottom-up calculation
    for ($i = $N - 2; $i >= 0; $i--)
    {
        for ($j = 0; $j < $N - $i; $j++)
        {
 
            // For each element, check both
            // elements just below the number
            // and below left to the number
            // add the maximum of them to it
            if ($j - 1 >= 0)
                $tri[$i][$j] += max($tri[$i + 1][$j],
                                    $tri[$i + 1][$j - 1]);
            else
                $tri[$i][$j] += $tri[$i + 1][$j];
 
            $ans = max($ans, $tri[$i][$j]);
        }
    }
 
    // Return the maximum sum
    return $ans;
}
 
// Driver Code
$tri = array(array( 1, 5, 3 ),
             array( 4, 8, 0 ),
             array( 1, 0, 0 ));
 
echo maxPathSum($tri);
 
// This code is contributed by chandan_jnu
?>

Javascript




<script>
//Javascript program implementation of
// Max sum problem in a triangle
 
N = 3;
 
// Function for finding maximum sum
function maxPathSum(tri)
{
    var ans = 0;
 
    // Loop for bottom-up calculation
    for (var i = N - 2; i >= 0; i--) {
        for (var j = 0; j < N - i; j++) {
 
            // For each element, check both
            // elements just below the number
            // and below left to the number
            // add the maximum of them to it
            if (j - 1 >= 0)
                tri[i][j] += Math.max(tri[i + 1][j],
                                 tri[i + 1][j - 1]);
            else
                tri[i][j] += tri[i + 1][j];
 
            ans = Math.max(ans, tri[i][j]);
        }
    }
 
    // Return the maximum sum
    return ans;
}
 
    var tri =  [[ 1, 5, 3 ],
                      [ 4, 8, 0 ],
                      [ 1, 0, 0 ]];
    document.write(maxPathSum(tri));
 
//This code is contributed by SoumikMondal
</script>

Output

14

Time Complexity: O(N2)

Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!