Maximum sum of a path in a Right Number Triangle in C++

C++Server Side ProgrammingProgramming

Problem statement

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

Example

If given input is:
3
4 5
1 10 7
Then maximum sum is 18 as (3 + 5 + 10).

Algorithm

The idea is to find largest sum ending at every cell of last row and return maximum of these sums.

We can recursively compute these sums by recursively considering above two cells

Since there are overlapping sub-problems, we use dynamic programming to find the maximum sum ending at particular cell of last row

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int maxSum(int tringle[][3], int n){
   if (n > 1) {
      tringle[1][1] = tringle[1][1] + tringle[0][0];
      tringle[1][0] = tringle[1][0] + tringle[0][0];
   }
   for(int i = 2; i < n; i++) {
      tringle[i][0] = tringle[i][0] + tringle[i-1][0];
      tringle[i][i] = tringle[i][i] + tringle[i-1][i-1];
      for (int j = 1; j < i; j++){
         if (tringle[i][j] + tringle[i-1][j-1] >=tringle[i][j] + tringle[i-1][j]) {
            tringle[i][j] = tringle[i][j] + tringle[i-1][j-1];
         } else {
            tringle[i][j] = tringle[i][j]+tringle[i-1][j];
         }
      }
   }
   int max = tringle[n - 1][0];
   for(int i = 1;i < n; i++) {
      if(max < tringle[n-1][i]) {
         max=tringle[n-1][i];
      }
   }
   return max;
}
int main(){
   int tringle[3][3] = {
      {3},
      {4,5},
      {1,10,7}
   };
   cout << "Maximum sum = " << maxSum(tringle, 3) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum sum = 18
raja
Published on 30-Jan-2020 12:17:36
Advertisements