Maximum sum possible from given Matrix by performing given operations | Java program for the above approach ; Function to print the maximum sum ; Dp table ; Initializing dp array with 0 s ; Base case ; Traverse each column ; Update answer for both rows ; Print the maximum sum ; Driver Code ; Given array ; Number of Columns ; Function calls
import java . io . * ; import java . util . * ; class GFG { static void maxSum ( int [ ] [ ] arr , int n , int m ) { int [ ] [ ] dp = new int [ n ] [ m + 1 ] ; for ( int i = 0 ; i < 2 ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { dp [ i ] [ j ] = 0 ; } } dp [ 0 ] [ m - 1 ] = arr [ 0 ] [ m - 1 ] ; dp [ 1 ] [ m - 1 ] = arr [ 1 ] [ m - 1 ] ; for ( int j = m - 2 ; j >= 0 ; j -- ) { for ( int i = 0 ; i < 2 ; i ++ ) { if ( i == 1 ) { dp [ i ] [ j ] = Math . max ( arr [ i ] [ j ] + dp [ 0 ] [ j + 1 ] , arr [ i ] [ j ] + dp [ 0 ] [ j + 2 ] ) ; } else { dp [ i ] [ j ] = Math . max ( arr [ i ] [ j ] + dp [ 1 ] [ j + 1 ] , arr [ i ] [ j ] + dp [ 1 ] [ j + 2 ] ) ; } } } System . out . println ( Math . max ( dp [ 0 ] [ 0 ] , dp [ 1 ] [ 0 ] ) ) ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 50 , 21 , 5 } , { 2 , 10 , 10 , 5 } } ; int N = arr [ 0 ] . length ; maxSum ( arr , 2 , N ) ; } }