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 readonly answer ; Driver code
using System ; class GFG { static int maximumSum ( int [ ] A , int [ ] B , int length , int X , int Y ) { int l = length ; int l1 = Math . Min ( length , X ) ; int l2 = Math . Min ( length , Y ) ; int [ , ] dp = new int [ l1 + 1 , l2 + 1 ] ; int max_sum = int . MinValue ; for ( int 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 ( int 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 ( int i = 1 ; i <= l1 ; i ++ ) { for ( int 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 ; } public static void Main ( String [ ] args ) { int [ ] A = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int [ ] B = new int [ ] { 5 , 4 , 3 , 2 , 1 } ; int X = 3 , Y = 2 ; int N = A . Length ; Console . WriteLine ( maximumSum ( A , B , N , X , Y ) ) ; } }