Maximum sum by picking elements from two arrays in order | Set 2 | Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the dp [ ] [ ] for base case when all elements are selected from A [ ] ; Fill the dp [ ] [ ] for base case when all elements are selected from B [ ] ; Return the final answer ; Driver Program
function maximumSum ( A , B , length , X , Y ) { var l = length ; var l1 = Math . min ( length , X ) ; var l2 = Math . min ( length , Y ) ; var dp = Array . from ( Array ( l1 + 1 ) , ( ) => Array ( l2 + 1 ) . fill ( 0 ) ) ; dp [ 0 ] [ 0 ] = 0 ; var max_sum = - 1000000000 ; for ( var i = 1 ; i <= l1 ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + A [ i - 1 ] ; max_sum = Math . max ( max_sum , dp [ i ] [ 0 ] ) ; } for ( var i = 1 ; i <= l2 ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + B [ i - 1 ] ; max_sum = Math . max ( max_sum , dp [ 0 ] [ i ] ) ; } for ( var i = 1 ; i <= l1 ; i ++ ) { for ( var j = 1 ; j <= l2 ; j ++ ) { if ( i + j <= l ) dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] + A [ i + j - 1 ] , dp [ i ] [ j - 1 ] + B [ i + j - 1 ] ) ; max_sum = Math . max ( dp [ i ] [ j ] , max_sum ) ; } } return max_sum ; } var A = [ 1 , 2 , 3 , 4 , 5 ] ; var B = [ 5 , 4 , 3 , 2 , 1 ] ; var X = 3 , Y = 2 ; var N = A . length ; document . write ( maximumSum ( A , B , N , X , Y ) ) ;