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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

## 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[], int n){
if (n > 1) {
tringle = tringle + tringle;
tringle = tringle + tringle;
}
for(int i = 2; i < n; i++) {
tringle[i] = tringle[i] + tringle[i-1];
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];
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},
{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