Maximize the Sum of the given array using given operations | 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
def compare ( p1 , p2 ) : NEW_LINE INDENT return p1 [ 0 ] > p2 [ 0 ] NEW_LINE DEDENT def maximiseScore ( A , B , K , N ) : NEW_LINE INDENT pairs = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pairs . append ( [ A [ i ] , B [ i ] ] ) NEW_LINE DEDENT pairs . sort ( key = lambda x : x [ 0 ] , reverse = True ) NEW_LINE Sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( pairs [ i ] [ 1 ] == 0 ) : NEW_LINE INDENT Sum += pairs [ i ] [ 0 ] NEW_LINE DEDENT elif ( pairs [ i ] [ 1 ] == 1 ) : NEW_LINE INDENT if ( K > 0 ) : NEW_LINE INDENT Sum += pairs [ i ] [ 0 ] NEW_LINE K -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT Sum -= pairs [ i ] [ 0 ] NEW_LINE DEDENT DEDENT DEDENT return Sum NEW_LINE DEDENT A = [ 5 , 4 , 6 , 2 , 8 ] NEW_LINE B = [ 1 , 0 , 1 , 1 , 0 ] NEW_LINE K = 2 NEW_LINE N = len ( A ) NEW_LINE print ( maximiseScore ( A , B , K , N ) ) NEW_LINE