Maximize the Sum of the given array using given operations | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( pair < int , int > p1 , pair < int , int > p2 ) { return p1 . first > p2 . first ; } int maximiseScore ( int A [ ] , int B [ ] , int K , int N ) { vector < pair < int , int > > pairs ( N ) ; for ( int i = 0 ; i < N ; i ++ ) { pairs [ i ] = make_pair ( A [ i ] , B [ i ] ) ; } sort ( pairs . begin ( ) , pairs . end ( ) , compare ) ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( pairs [ i ] . second == 0 ) { sum += pairs [ i ] . first ; } else if ( pairs [ i ] . second == 1 ) { if ( K > 0 ) { sum += pairs [ i ] . first ; K -- ; } else { sum -= pairs [ i ] . first ; } } } return sum ; } int main ( ) { int A [ ] = { 5 , 4 , 6 , 2 , 8 } ; int B [ ] = { 1 , 0 , 1 , 1 , 0 } ; int K = 2 ; int N = sizeof ( A ) / sizeof ( int ) ; cout << maximiseScore ( A , B , K , N ) ; return 0 ; }