Maximum path sum in an Inverted triangle in C++


In this problem, we are given numbers in the form of an inverted triangle. Our task is to create a program that will find the maximum path sum in an inverted triangle.

Inverted triangle form of number is an arrangement when the first row contains n elements, second n-1, and so on.

Here, we have to find the maximum sum that can 3 be obtained by adding one element from each row.

Let’s take an example to understand the problem −

Input 

5 1 9
 3 6
  2

Output − 17

Explanation − Here, I have found the path from the last row to the top row, considering the maximum possible elements in the path.

To solve this problem, we will be using the dynamic programming approach, similar to what we apply in the case of minimum cost path problems. Here, we will start from the bottom and then find the path the gives the maximum sum.

Prior to this we will consider the inverted triangle as a regular matrix by shift all number of left and add 0’s to the remaining places.

Example

Program to find the maximum path sum in an inverted triangle −

 Live Demo

#include <iostream>
using namespace std;
#define N 3
int findMaxPathSumInvertedTriangle(int matrix[][N]){
   int maxSum = 0;
   for (int i = N - 2; i >= 0; i--) {
      for (int j = 0; j < N - i; j++) {
         if (j - 1 >= 0)
            matrix[i][j] += max(matrix[i + 1][j], matrix[i + 1][j - 1]);
         else
            matrix[i][j] += matrix[i + 1][j];
            maxSum = max(maxSum, matrix[i][j]);
      }
   }
   return maxSum;
}
int main(){
   int invertedTriangle[N][N] = {
      {5, 1, 9},
      {3, 6, 0},
      {2, 0, 0}};
   cout<<"The maximum path sum is "<<findMaxPathSumInvertedTriangle(invertedTriangle);
   return 0;
}

Output

The maximum path sum is 17

Updated on: 03-Jun-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements