Maximize sum of topmost elements of S stacks by popping at most N elements | C # program to maximize the sum of top of the stack values 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 ; Driver code ; Number of stacks ; Length of each stack ; Maximum elements that can be popped
using System ; class GFG { static int maximumSum ( int S , int M , int N , int [ , ] stacks ) { int [ , ] dp = new int [ S + 1 , N + 1 ] ; for ( int i = 0 ; i < S ; i ++ ) { for ( int j = 0 ; j <= N ; j ++ ) { for ( int 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 ] ) ; } } } int result = int . MinValue ; for ( int i = 0 ; i <= N ; i ++ ) { result = Math . Max ( result , dp [ S , i ] ) ; } return result ; } public static void Main ( String [ ] args ) { int S = 2 ; int M = 4 ; int [ , ] stacks = { { 2 , 6 , 4 , 5 } , { 1 , 6 , 15 , 10 } } ; int N = 3 ; Console . Write ( maximumSum ( S , M , N , stacks ) ) ; } }