Maximum sum by picking elements from two arrays in order | Set 2 | C ++ program to find maximum sum possible by selecting an element from one of two arrays for every index ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int A [ ] , int B [ ] , int length , int X , int Y ) { int l = length ; int l1 = min ( length , X ) ; int l2 = min ( length , Y ) ; int dp [ l1 + 1 ] [ l2 + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] [ 0 ] = 0 ; int max_sum = INT_MIN ; for ( int i = 1 ; i <= l1 ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + A [ i - 1 ] ; max_sum = max ( max_sum , dp [ i ] [ 0 ] ) ; } for ( int i = 1 ; i <= l2 ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + B [ i - 1 ] ; max_sum = max ( max_sum , dp [ 0 ] [ i ] ) ; } for ( int i = 1 ; i <= l1 ; i ++ ) { for ( int j = 1 ; j <= l2 ; j ++ ) { if ( i + j <= l ) dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] + A [ i + j - 1 ] , dp [ i ] [ j - 1 ] + B [ i + j - 1 ] ) ; max_sum = max ( dp [ i ] [ j ] , max_sum ) ; } } return max_sum ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 } ; int B [ ] = { 5 , 4 , 3 , 2 , 1 } ; int X = 3 , Y = 2 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maximumSum ( A , B , N , X , Y ) ; return 0 ; }