Maximize Array sum by swapping at most K elements with another array | Java 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
import java . util . * ; class GFG { static void maximumSum ( int a [ ] , int b [ ] , int k , int n ) { int i , j ; Arrays . sort ( a ) ; Arrays . sort ( b ) ; for ( i = 0 , j = n - 1 ; i < k ; i ++ , j -- ) { if ( a [ i ] < b [ j ] ) { int temp = a [ i ] ; a [ i ] = b [ j ] ; b [ j ] = temp ; } else break ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) sum += a [ i ] ; System . out . print ( sum + "NEW_LINE"); } public static void main ( String [ ] args ) { int K = 1 ; int A [ ] = { 2 , 3 , 4 } ; int B [ ] = { 6 , 8 , 5 } ; int N = A . length ; maximumSum ( A , B , K , N ) ; } }