Maximize sum of subsets from two arrays having no consecutive values | C ++ program for the above approach ; Function to calculate maximum subset sum ; Initialize array to store dp states ; Base Cases ; Pre initializing for dp [ 0 ] & dp [ 1 ] ; Calculating dp [ index ] based on above formula ; Print maximum subset sum ; Driver Code ; Given arrays ; Length of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSubsetSum ( int arr1 [ ] , int arr2 [ ] , int length ) { int dp [ length + 1 ] ; if ( length == 1 ) { cout << ( max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ; return ; } if ( length == 2 ) { cout << ( max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ) ; return ; } else { dp [ 0 ] = max ( arr1 [ 0 ] , arr2 [ 0 ] ) ; dp [ 1 ] = max ( max ( arr1 [ 1 ] , arr2 [ 1 ] ) , max ( arr1 [ 0 ] , arr2 [ 0 ] ) ) ; int index = 2 ; while ( index < length ) { dp [ index ] = max ( max ( arr1 [ index ] , arr2 [ index ] ) , max ( max ( arr1 [ index ] + dp [ index - 2 ] , arr2 [ index ] + dp [ index - 2 ] ) , dp [ index - 1 ] ) ) ; ++ index ; } cout << ( dp [ length - 1 ] ) ; } } int main ( ) { int arr1 [ ] = { -1 , -2 , 4 , -4 , 5 } ; int arr2 [ ] = { -1 , -2 , -3 , 4 , 10 } ; int length = 5 ; maximumSubsetSum ( arr1 , arr2 , length ) ; return 0 ; }