Maximize sum of topmost elements of S stacks by popping at most N elements | Function for computing the maximum sum at the top of the stacks after popping at most N elements from S stack ; Constructing a dp matrix of dimensions ( S + 1 ) x ( N + 1 ) ; Loop over all i stacks ; Store the maximum of popping j elements up to the current stack by popping k elements from current stack and j - k elements from all previous stacks combined ; Store the maximum sum of popping N elements across all stacks ; dp [ S ] [ N ] has the maximum sum ; Number of stacks ; Length of each stack ; Maximum elements that can be popped
function maximumSum ( S , M , N , stacks ) { var dp = Array . from ( Array ( S + 1 ) , ( ) => Array ( N + 1 ) . fill ( 0 ) ) ; for ( var i = 0 ; i < S ; i ++ ) { for ( var j = 0 ; j <= N ; j ++ ) { for ( var k = 0 ; k <= Math . min ( j , M ) ; k ++ ) { dp [ i + 1 ] [ j ] = Math . max ( dp [ i + 1 ] [ j ] , stacks [ i ] [ k ] + dp [ i ] [ j - k ] ) ; } } } var result = - 1000000000 ; for ( var i = 0 ; i <= N ; i ++ ) { result = Math . max ( result , dp [ S ] [ i ] ) ; } return result ; } var S = 2 ; var M = 4 ; var stacks = [ [ 2 , 6 , 4 , 5 ] , [ 1 , 6 , 15 , 10 ] ] ; var N = 3 ; document . write ( maximumSum ( S , M , N , stacks ) ) ;