Maximum non | Function to find the maximum product from the top left and bottom right cell of the given matrix grid [ ] [ ] ; Store dimension of grid ; Stores maximum product path ; Stores minimum product path ; Traverse the grid and update maxPath and minPath array ; Initialize to inf and - inf ; Base Case ; Calculate for row : ; Update the maximum ; Update the minimum ; Calculate for column : ; Update the maximum ; Update the minimum ; Update maxPath and minPath ; If negative product ; Otherwise ; Given matrix mat [ ] [ ] ; Function Call
function maxProductPath ( grid ) { var n = grid . length ; var m = grid [ 0 ] . length ; var maxPath = Array . from ( Array ( n ) , ( ) => Array ( m ) . fill ( 0 ) ) ; var minPath = Array . from ( Array ( n ) , ( ) => Array ( m ) . fill ( 0 ) ) ; for ( var i = 0 ; i < n ; i ++ ) { for ( var j = 0 ; j < m ; j ++ ) { var mn = 1000000000 ; var mx = - 1000000000 ; if ( i == 0 && j == 0 ) { mx = grid [ i ] [ j ] ; mn = grid [ i ] [ j ] ; } if ( i > 0 ) { var tempmx = Math . max ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) ; mx = Math . max ( mx , tempmx ) ; var tempmn = Math . min ( ( maxPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) , ( minPath [ i - 1 ] [ j ] * grid [ i ] [ j ] ) ) ; mn = Math . min ( mn , tempmn ) ; } if ( j > 0 ) { var tempmx = Math . max ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) ; mx = Math . max ( mx , tempmx ) ; var tempmn = Math . min ( ( maxPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) , ( minPath [ i ] [ j - 1 ] * grid [ i ] [ j ] ) ) ; mn = Math . min ( mn , tempmn ) ; } maxPath [ i ] [ j ] = mx ; minPath [ i ] [ j ] = mn ; } } if ( maxPath [ n - 1 ] [ m - 1 ] < 0 ) return - 1 ; else return ( maxPath [ n - 1 ] [ m - 1 ] ) ; } var mat = [ [ 1 , - 2 , 1 ] , [ 1 , - 2 , 1 ] , [ 3 , - 4 , 1 ] ] ; document . write ( maxProductPath ( mat ) ) ;