Maximum non | C # program for the above approach ; 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 ; Driver Code ; Given matrix mat [ ] [ ] ; Function Call
using System ; class GFG { static int maxProductPath ( int [ , ] grid ) { int n = grid . GetLength ( 0 ) ; int m = grid . GetLength ( 1 ) ; int [ , ] maxPath = new int [ n , m ] ; int [ , ] minPath = new int [ n , m ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { int mn = Int32 . MaxValue ; int mx = Int32 . MinValue ; if ( i == 0 && j == 0 ) { mx = grid [ i , j ] ; mn = grid [ i , j ] ; } if ( i > 0 ) { int tempmx = Math . Max ( ( maxPath [ i - 1 , j ] * grid [ i , j ] ) , ( minPath [ i - 1 , j ] * grid [ i , j ] ) ) ; mx = Math . Max ( mx , tempmx ) ; int 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 ) { int tempmx = Math . Max ( ( maxPath [ i , j - 1 ] * grid [ i , j ] ) , ( minPath [ i , j - 1 ] * grid [ i , j ] ) ) ; mx = Math . Max ( mx , tempmx ) ; int 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 ] ) ; } } static public void Main ( ) { int [ , ] mat = { { 1 , - 2 , 1 } , { 1 , - 2 , 1 } , { 3 , - 4 , 1 } } ; Console . WriteLine ( maxProductPath ( mat ) ) ; } }