Maximize product of same | Java implementation to maximize product of same - indexed elements of same size subsequences ; Utility function to find the maximum ; Utility function to find the maximum scalar product from the equal length sub - sequences taken from the two given array ; Return a very small number if index is invalid ; If the sub - problem is already evaluated , then return it ; Take the maximum of all the recursive cases ; Function to find maximum scalar product from same size sub - sequences taken from the two given array ; Initialize a 2 - D array for memoization ; Driver Code
class GFG { static final int INF = 10000000 ; static int maximum ( int A , int B , int C , int D ) { return Math . max ( Math . max ( A , B ) , Math . max ( C , D ) ) ; } static int maxProductUtil ( int X , int Y , int [ ] A , int [ ] B , int [ ] [ ] dp ) { if ( X < 0 Y < 0 ) return - INF ; if ( dp [ X ] [ Y ] != - 1 ) return dp [ X ] [ Y ] ; dp [ X ] [ Y ] = maximum ( A [ X ] * B [ Y ] + maxProductUtil ( X - 1 , Y - 1 , A , B , dp ) , A [ X ] * B [ Y ] , maxProductUtil ( X - 1 , Y , A , B , dp ) , maxProductUtil ( X , Y - 1 , A , B , dp ) ) ; return dp [ X ] [ Y ] ; } static int maxProduct ( int A [ ] , int N , int B [ ] , int M ) { int [ ] [ ] dp = new int [ N ] [ M ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } return maxProductUtil ( N - 1 , M - 1 , A , B , dp ) ; } public static void main ( String [ ] args ) { int a [ ] = { - 2 , 6 , - 2 , - 5 } ; int b [ ] = { - 3 , 4 , - 2 , 8 } ; int n = a . length ; int m = b . length ; System . out . print ( maxProduct ( a , n , b , m ) ) ; } }