-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMaximum path sum in matrix.cpp
38 lines (35 loc) · 1.05 KB
/
Maximum path sum in matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c].
Matrix [r+1] [c]
Matrix [r+1] [c-1]
Matrix [r+1] [c+1]
Starting from any column in row 0 return the largest sum of any of the paths up to row N-1.
Example 1:
Input: N = 2
Matrix = {{348, 391},
{618, 193}}
Output: 1009
Explaination: The best path is 391 -> 618.
It gives the sum = 1009.
*/
int maximumPath(int N, vector<vector<int>> Matrix)
{
for(int i=1;i<N;i++){
for(int j=0;j<N;j++){
if(j>0 and j<N-1){
Matrix[i][j] += max({Matrix[i-1][j],Matrix[i-1][j-1],Matrix[i-1][j+1]});
}
else if(j>0){
Matrix[i][j] += max (Matrix[i-1][j],Matrix[i-1][j-1]);
}
else if(j<N-1){
Matrix[i][j] += max(Matrix[i-1][j],Matrix[i-1][j+1]);
}
}
}
int res=0;
for(int i=0;i<N;i++){
res = max(Matrix[N-1][i],res);
}
return res;
}