Maximize sum by choosing elements from different section of a matrix | Javascript program for the above approach ; Function to find the maximum value ; Dp table ; Fill the dp in bottom up manner ; Maximum of the three sections ; Maximum of the first section ; Maximum of the second section ; Maximum of the third section ; If we choose element from section 1 , we cannot have selection from same section in adjacent rows ; Print the maximum sum ; Driver code
const n = 6 , m = 6 ; function maxSum ( arr ) { const dp = new Array ( n + 1 ) . fill ( 0 ) . map ( ( ) => new Array ( 3 ) . fill ( 0 ) ) ; for ( var i = 0 ; i < n ; i ++ ) { var m1 = 0 , m2 = 0 , m3 = 0 ; for ( var j = 0 ; j < m ; j ++ ) { if ( parseInt ( j / ( m / 3 ) ) == 0 ) { m1 = Math . max ( m1 , arr [ i ] [ j ] ) ; } else if ( parseInt ( j / ( m / 3 ) ) == 1 ) { m2 = Math . max ( m2 , arr [ i ] [ j ] ) ; } else if ( parseInt ( j / ( m / 3 ) ) == 2 ) { m3 = Math . max ( m3 , arr [ i ] [ j ] ) ; } } dp [ i + 1 ] [ 0 ] = Math . max ( dp [ i ] [ 1 ] , dp [ i ] [ 2 ] ) + m1 ; dp [ i + 1 ] [ 1 ] = Math . max ( dp [ i ] [ 0 ] , dp [ i ] [ 2 ] ) + m2 ; dp [ i + 1 ] [ 2 ] = Math . max ( dp [ i ] [ 1 ] , dp [ i ] [ 0 ] ) + m3 ; } document . write ( parseInt ( Math . max ( Math . max ( dp [ n ] [ 0 ] , dp [ n ] [ 1 ] ) , dp [ n ] [ 2 ] ) ) + " " ) ; } arr = [ [ 1 , 3 , 5 , 2 , 4 , 6 ] , [ 6 , 4 , 5 , 1 , 3 , 2 ] , [ 1 , 3 , 5 , 2 , 4 , 6 ] , [ 6 , 4 , 5 , 1 , 3 , 2 ] , [ 6 , 4 , 5 , 1 , 3 , 2 ] , [ 1 , 3 , 5 , 2 , 4 , 6 ] ] ; maxSum ( arr ) ;