![]() |
VOOZH | about |
Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1).
However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum of elements satisfying the allowed moves.
Examples:
Input:
mat[][] = {{100, -350, -200},
{-100, -300, 700}}
Output: 500
Explanation:
Path followed is 100 -> -300 -> 700
Input:
mat[][] = {{500, 100, 230},
{1000, 300, 100},
{200, 1000, 200}}
Explanation:
Path followed is 500 -> 1000 -> 300 -> 1000 -> 200
Naive Approach: Recursion
Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.
3000
Time Complexity: O(2N*M)
Auxiliary Space: O(N*M)
2. : Dynamic programming is used to solve the above problem in a recursive way.
Below is the implementation of the above approach:
3000
Time Complexity: O(N*M)
Auxiliary Space: O(N*M) + O(N+M) -> O(NxM) is for the declared matrix of size nxm and O(N+M) is for the stack space (maximum recursive recursion calls).
3. : This approach will remove the extra space complexity i.e O(N+M) caused by recursion in the above approach.
500
Time complexity: O(NxM)
Auxiliary Space: O(NxM)