Maximum non-negative product of a path from top left to bottom right of given Matrix
Given an integer matrix mat of dimensions N * M, the task is to print the maximum product of matrix elements in the path from the top-left cell (0, 0) to the bottom-right cell (N – 1, M – 1) of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) or (i, j + 1). If the maximum product is negative, then print “-1”.
Input: mat = [[1, -2, 1], [1, -2, 1], [3, -4, 1]]
Explanation: The path from top left to bottom right with maximum product is (0, 0) → (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) = 1 * 1 * ( -2 ) * ( -4 ) * ( 1 ) = 8.
Therefore, the maximum positive product is 8.
Input: mat = [[-1, -2, -3], [-2, -3, -3], [-3, -3, -2]]
Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2). Therefore, print -1.
Naive Approach: The simplest approach to solve to recursively traverse from the top-left cell and generate all possible paths from top left to the bottom-right cell by moving rightwards and downwards from each cell. Find the product for each path generated and print the maximum among them.
Time Complexity: O(2max(N, M))
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming. Follow the steps below to solve the problem:
- Initialize matrices maxPath and minPath, to store maximum and minimum product of paths respectively.
- The idea is to also keep track of the maximum negative product obtained so far, because if any negative product is encountered, then the negative product multiplied by maximum negative product can generate maximum positive product.
- To reach index (i, j), as the possible moves allowed are rightward and downward, so the maximum product can be maximum product or minimum product till (i – 1, j)th index or (i, j – 1)th index multiplied by the element at index (i, j).
- After completing the above steps, if the value of maxPath[M – 1][N – 1] is non-negative, then print it as the positive product path. Otherwise, print “-1”.
Below is the implementation of the above approach:
Time Complexity: O(M*N)
Auxiliary Space: O(M*N)