# Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row 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

Best Seller

66 Lectures 5.5 hours

In this tutorial, we will be discussing a program to find maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row

For this we will be provided with a matrix with possible moves of (i+1, j), (i+1, j-1), (i+1, j+1). Our task is to start from zeroth position and move to last row finding out the maximum sum path.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
#define N 4
//finding maximum sum path
int MaximumPath(int Mat[][N]) {
int result = 0 ;
int dp[N][N+2];
memset(dp, 0, sizeof(dp));
for (int i = 0 ; i < N ; i++)
dp[0][i+1] = Mat[0][i];
for (int i = 1 ; i < N ; i++)
for (int j = 1 ; j <= N ; j++)
dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + Mat[i][j-1] ;
for (int i=0; i<=N; i++)
result = max(result, dp[N-1][i]);
return result ;
}
int main() {
int Mat[4][4] = {
{ 4, 2 , 3 , 4 },
{ 2 , 9 , 1 , 10},
{ 15, 1 , 3 , 0 },
{ 16 ,92, 41, 44 }
};
cout << MaximumPath ( Mat ) <<endl ;
return 0;
}

## Output

120
Updated on 09-Sep-2020 12:02:53