Maximum Path Sum in the matrix
You have been given an N*M matrix filled with integer numbers, find the maximum sum that can be obtained from a path starting from any cell in the first row to any cell in the last row.
From a cell in a row, you can move to another cell directly below that row, or diagonally below left or right. So from a particular cell (row, col), we can move in three directions i.e.
Down: (row+1,col)
Down left diagonal: (row+1,col-1)
Down right diagonal: (row+1, col+1)
Input format :
The first line contains an integer 'T', which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains two Integers 'N' and 'M' where 'N' denotes the number of rows in the given matrix. And 'M' denotes the number of columns in the given matrix.
The next 'N' line of each test case contains 'M' space-separated integers denoting the cell elements.
Output format :
For each test case/query, print the maximum sum that can be obtained by taking a path as described above.
Output for every test case will be printed in a separate line.
Note :
You do not need to print anything. It has already been taken care of.
Constraints :
1 <= T <= 50
1 <= N <= 100
1 <= M <= 100
-10^4 <= matrix[i][j] <= 10^4
Where 'T' is the number of test cases.
Where 'N' is the number of rows in the given matrix, and 'M' is the number of columns in the given matrix.
And, matrix[i][j] denotes the value at (i,j) cell in the matrix.
Time Limit: 1sec
CodingNinjas
author
2y
Brute Force
The basic approach is that we are going to explore all possible paths recursively from the first row for each cell and return the maximum sum among all paths. Steps are as follows:
- Start exp...read more
CodingNinjas
author
2y
Using Memoization
If we draw the recursion tree for the recursive solution of Approach-1, we can observe that there is a lot of overlapping subproblems, there is only N*M distinct recursive call. Since...read more
CodingNinjas
author
2y
Using Dynamic Programming
We are given an N*M matrix. Our idea behind this approach is while traversing in the given matrix, and we will keep updating the matrix with the best sum path till now. That m...read more
Add answer anonymously...
Top Quess Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app