Maximum sum possible from given Matrix by performing given operations | 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 ; Given array ; Number of Columns ; Function calls
function maxSum ( arr , n , m ) { let dp = new Array ( n ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < 2 ; i ++ ) { for ( let 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 ( let j = m - 2 ; j >= 0 ; j -- ) { for ( let 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 ] ) ; } } } document . write ( Math . max ( dp [ 0 ] [ 0 ] , dp [ 1 ] [ 0 ] ) ) ; } let arr = [ [ 1 , 50 , 21 , 5 ] , [ 2 , 10 , 10 , 5 ] ] ; let N = arr [ 0 ] . length ; maxSum ( arr , 2 , N ) ;