Maximize maximum possible subarray sum of an array by swapping with elements from another array | C ++ program for the above approach ; Function to find the maximum subarray sum possible by swapping elements from array arr [ ] with that from array brr [ ] ; Stores elements from the arrays arr [ ] and brr [ ] ; Store elements of array arr [ ] and brr [ ] in the vector crr ; Sort the vector crr in descending order ; Stores maximum sum ; Calculate the sum till the last index in crr [ ] which is less than N which contains a positive element ; Print the sum ; Driver code ; Given arrays and respective lengths ; Calculate maximum subarray sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSum ( int * arr , int * brr , int N , int K ) { vector < int > crr ; for ( int i = 0 ; i < N ; i ++ ) { crr . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < K ; i ++ ) { crr . push_back ( brr [ i ] ) ; } sort ( crr . begin ( ) , crr . end ( ) , greater < int > ( ) ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( crr [ i ] > 0 ) { sum += crr [ i ] ; } else { break ; } } cout << sum << endl ; } int main ( ) { int arr [ ] = { 7 , 2 , -1 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int brr [ ] = { 1 , 2 , 3 , 2 } ; int K = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; maxSum ( arr , brr , N , K ) ; }