Given a matrix of N * M. Find the maximum path sum in matrix. The maximum path is sum of all elements from first row to last row where you are allowed to move only down or diagonally to left or right. You can start from any element in first row.
Input : mat = 10 10 2 0 20 4 1 0 0 30 2 5 0 10 4 0 2 0 1 0 2 20 0 4 Output : 74 The maximum sum path is 20-30-4-20. Input : mat = 1 2 3 9 8 7 4 5 6 Output : 17 The maximum sum path is 3-8-6.
We are given a matrix of N * M. To find max path sum first we have to find max value in first row of matrix. Store this value in res. Now for every element in matrix update element with max value which can be included in max path. If the value is greater then res then update res. In last return res which consists of max path sum value.
Time Complexity: O(N*M)
This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum sum path in a matrix from top to bottom
- Maximum sum path in a matrix from top to bottom and back
- Paths from entry to exit in matrix and maximum path sum
- Find maximum path sum in a 2D matrix when exactly two left moves are allowed
- Maximum sum path in a matrix from top-left to bottom-right
- Maximum sum path in a Matrix
- Maximum weight path ending at any element of last row in a matrix
- Maximum decimal value path in a binary matrix
- Find maximum path length in a binary matrix
- Maximum XOR of a path from top-left to bottom-right cell of given Matrix
- Maximise matrix sum by following the given Path
- Maximize path sum from top-left cell to all other cells of a given Matrix
- Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
- Maximum trace possible for any sub-matrix of the given matrix
- Find the longest path in a matrix with given constraints
- Longest Increasing Path in Matrix
- Check for possible path in 2D matrix
- Minimum odd cost path in a matrix
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Minimum cost path in a Matrix by moving only on value difference of X