Maximize the Sum of the given array using given operations | Java program to maximise the sum of the given array ; Comparator to sort the array in ascending order ; Function to maximise the sum of the given array ; Stores { A [ i ] , B [ i ] } pairs ; Sort in descending order of the values in the array A [ ] ; Stores the maximum sum ; If B [ i ] is equal to 0 ; Simply add A [ i ] to the sum ; Add the highest K numbers ; Subtract from the sum ; Return the sum ; Driver Code
import java . util . * ; class Pair implements Comparable < Pair > { int first , second ; Pair ( int x , int y ) { first = x ; second = y ; } public int compareTo ( Pair p ) { return p . first - first ; } } class GFG { static int maximiseScore ( int A [ ] , int B [ ] , int K , int N ) { ArrayList < Pair > pairs = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { pairs . add ( new Pair ( A [ i ] , B [ i ] ) ) ; } Collections . sort ( pairs ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( pairs . get ( i ) . second == 0 ) { sum += pairs . get ( i ) . first ; } else if ( pairs . get ( i ) . second == 1 ) { if ( K > 0 ) { sum += pairs . get ( i ) . first ; K -- ; } else { sum -= pairs . get ( i ) . first ; } } } return sum ; } public static void main ( String [ ] args ) { int A [ ] = { 5 , 4 , 6 , 2 , 8 } ; int B [ ] = { 1 , 0 , 1 , 1 , 0 } ; int K = 2 ; int N = A . length ; System . out . print ( maximiseScore ( A , B , K , N ) ) ; } }