Maximize Array sum by swapping at most K elements with another array | C ++ implementation to find maximum sum of array A by swapping at most K elements with array B ; Function to find the maximum sum ; If element of array a is smaller than that of array b , swap them . ; Find sum of resultant array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSum ( int a [ ] , int b [ ] , int k , int n ) { int i , j ; sort ( a , a + n ) ; sort ( b , b + n ) ; for ( i = 0 , j = n - 1 ; i < k ; i ++ , j -- ) { if ( a [ i ] < b [ j ] ) swap ( a [ i ] , b [ j ] ) ; else break ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) sum += a [ i ] ; cout << sum << endl ; } int main ( ) { int K = 1 ; int A [ ] = { 2 , 3 , 4 } ; int B [ ] = { 6 , 8 , 5 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; maximumSum ( A , B , K , N ) ; return 0 ; }