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 firstname.lastname@example.org. 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.
- Maximum sum path in a matrix from top to bottom
- Maximum decimal value path in a binary matrix
- Maximum sum path in a matrix from top to bottom and back
- Maximum weight path ending at any element of last row in a matrix
- Find maximum path length in a binary matrix
- Check for possible path in 2D matrix
- Find whether there is path between two cells in matrix
- Minimum odd cost path in a matrix
- Longest Increasing Path in Matrix
- Find the longest path in a matrix with given constraints
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Path with maximum average value
- Maximum trace possible for any sub-matrix of the given matrix
- Maximum XOR value in matrix
- Find a sub matrix with maximum XOR