Path with maximum product in 2 | Python Program to find maximum product path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Function to find maximum product ; It will store the maximum product till a given cell . ; It will store the minimum product till a given cell ( for - ve elements ) ; If we are at topmost or leftmost , just copy the elements . ; If we 're not at the  above, we can consider  the above value. ; If we 're not on the  leftmost, we can consider  the left value. ; Store max & min product till i , j . ; Return the max product path from 0 , 0. N - 1 , M - 1. ; Driver Code ; Prmaximum product from ( 0 , 0 ) to ( N - 1 , M - 1 )
import sys NEW_LINE N = 3 ; NEW_LINE M = 3 ; NEW_LINE def maxProductPath ( arr ) : NEW_LINE INDENT maxPath = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE minPath = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT minVal = sys . maxsize ; NEW_LINE maxVal = - sys . maxsize ; NEW_LINE if ( i == 0 and j == 0 ) : NEW_LINE INDENT maxVal = arr [ i ] [ j ] ; NEW_LINE minVal = arr [ i ] [ j ] ; NEW_LINE DEDENT if ( i > 0 ) : NEW_LINE INDENT tempMax = max ( maxPath [ i - 1 ] [ j ] * arr [ i ] [ j ] , \ minPath [ i - 1 ] [ j ] * arr [ i ] [ j ] ) ; NEW_LINE maxVal = max ( maxVal , tempMax ) ; NEW_LINE tempMin = min ( maxPath [ i - 1 ] [ j ] * arr [ i ] [ j ] , \ minPath [ i - 1 ] [ j ] * arr [ i ] [ j ] ) ; NEW_LINE minVal = min ( minVal , tempMin ) ; NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT tempMax = max ( maxPath [ i ] [ j - 1 ] * arr [ i ] [ j ] , \ minPath [ i ] [ j - 1 ] * arr [ i ] [ j ] ) ; NEW_LINE maxVal = max ( maxVal , tempMax ) ; NEW_LINE tempMin = min ( maxPath [ i ] [ j - 1 ] * arr [ i ] [ j ] , \ minPath [ i ] [ j - 1 ] * arr [ i ] [ j ] ) ; NEW_LINE minVal = min ( minVal , tempMin ) ; NEW_LINE DEDENT maxPath [ i ] [ j ] = maxVal ; NEW_LINE minPath [ i ] [ j ] = minVal ; NEW_LINE DEDENT DEDENT return maxPath [ N - 1 ] [ M - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , - 2 , 3 ] , [ 4 , - 5 , 6 ] , [ - 7 , - 8 , 9 ] ] ; NEW_LINE print ( maxProductPath ( arr ) ) ; NEW_LINE DEDENT