Maximum path sum in a triangle in C++

C++Server Side ProgrammingProgramming

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

The elements are arranged starting from the 1st row with 1 one element and then next rows with an increasing number of elements till there are elements in the nth row.

So, the program will find the path that will provide the maximum sum of elements in the triangle. So, we have to find the path that will provide the maximum sum.

Let’s take an example to understand the problem −

Input

  1
 5 6
8 2 9

Output − 16

Explanation

The path from the top will return the maximum sum − 9+6+1 = 16

To solve this problem, we will be using dynamic programming that will use a bottom-up approach.

For this, we will first be left shift all the numbers of the triangle and adding 0’s at the end. This will make the triangle look like a matrix similar to what we see in the minimum cost path problem. After this, we will start from the bottom, and for each element, we will check for all possible paths and select the path which provides the maximum possible sum till that element. And traverse to the top in a similar way to find the maximum possible sum of the path in the triangle.

Example

Program to find the maximum path sum in the triangle −

 Live Demo

#include<iostream>
using namespace std;
#define N 3
int findMaxPathSumTriangle(int mat[][N], int m, int n){
   for (int i=m-1; i>=0; i--){
      for (int j=0; j<=i; j++){
         if (mat[i+1][j] > mat[i+1][j+1])
            mat[i][j] += mat[i+1][j];
         else
            mat[i][j] += mat[i+1][j+1];
      }
   }
   return mat[0][0];
}
int main() {
   int triangle[N][N] = {
      {1, 0, 0},
      {5, 6, 0},
      {8, 2, 9} };
   cout<<"The maximum path sum in triangle is "<<findMaxPathSumTriangle(triangle, 2, 2);
   return 0;
}

Output

The maximum path sum in triangle is 16
raja
Published on 10-Jan-2020 12:40:13
Advertisements