Maximize maximum possible subarray sum of an array by swapping with elements from another array | Java 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
import java . util . * ; class GFG { static void maxSum ( int arr [ ] , int brr [ ] , int N , int K ) { Vector < Integer > crr = new Vector < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { crr . add ( arr [ i ] ) ; } for ( int i = 0 ; i < K ; i ++ ) { crr . add ( brr [ i ] ) ; } Collections . sort ( crr ) ; Collections . reverse ( crr ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( crr . get ( i ) > 0 ) { sum += crr . get ( i ) ; } else { break ; } } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 2 , - 1 , 4 , 5 } ; int N = arr . length ; int brr [ ] = { 1 , 2 , 3 , 2 } ; int K = brr . length ; maxSum ( arr , brr , N , K ) ; } }