Maximum sum by picking elements from two arrays in order | Set 2 | Java 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 code
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 = Integer . MIN_VALUE ; 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 ; System . out . println ( maximumSum ( A , B , N , X , Y ) ) ; } }