Maximum sum possible from given Matrix by performing given operations | Java code for the above approach ; Function to print the maximum sum possible by selecting at most one element from each column such that no consecutive pairs are selected from a single row ; Initialize variables ; Traverse each column ; Print answer ; Driver Code ; Numberof columns
import java . io . * ; import java . util . * ; class GFG { static void maxSum ( int [ ] [ ] arr , int n ) { int r1 = 0 , r2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int temp = r1 ; r1 = Math . max ( r1 , r2 + arr [ 0 ] [ i ] ) ; r2 = Math . max ( r2 , temp + arr [ 1 ] [ i ] ) ; } System . out . println ( Math . max ( r1 , r2 ) ) ; } public static void main ( String args [ ] ) { int [ ] [ ] arr = { { 1 , 50 , 21 , 5 } , { 2 , 10 , 10 , 5 } } ; int n = arr [ 0 ] . length ; maxSum ( arr , n ) ; } }