Maximize the Sum of the given array using given operations - GeeksforGeeks

18 Apr, 2022
Given two arrays A[] and B[] consisting of N integers and an integer K, the task is to maximize the sum calculated from the array A[] by the following operations:  
For every index in B[] containing 0, the corresponding index in A[] is added to the sum.
For every index in B[] containing 1, add the value at the corresponding index in A[] to the sum for atmost K such indices. For the remaining indices, subtract from the sum.
Examples:
Input: A[] = {5, 4, 6, 2, 8}, B[] = {1, 0, 1, 1, 0}, K = 2 Output: 21 Explanation: Add A[1] and A[4] to the sum as B[1] = B[4] = 0 Therefore, sum = 4 + 8 = 12. Now, add A[0] and A[3] to the sum as K elements can be added. Finally, subtract 2 from the sum. Therefore, the maximum possible sum = 12 + 5 + 6 – 2 = 21Input: A[] = {5, 2, 1, 8, 10, 5}, B[] = {1, 1, 1, 1, 0, 0}, K = 3 Output: 29  
Approach:
Follow the steps below to solve the problem:  
Sort the array A[] in decreasing order.
To maximize the sum, add first K elements from the sorted array corresponding to which the index in B[] contains 1. Subtract the remaining such elements.
Add to the sum all the values in A[] corresponding to an index in B[] containing 0.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ Program to maximize the// sum of the given array#include <bits/stdc++.h>using namespace std; // Comparator to sort the array// in ascending orderbool compare(pairs<int, int> p1,             pairs<int, int> p2){    return p1.first > p2.first;} // Function to maximize the sum of// the given arrayint maximizeScore(int A[], int B[],                  int K, int N){     // Stores {A[i], B[i]} pairs    vector<pairs<int, int> > pairs(N);    for (int i = 0; i < N; i++) {        pairs[i] = make_pairs(A[i], B[i]);    }     // Sort in descending order of the    // values in the array A[]    sort(pairs.begin(), pairs.end(), compare);     // Stores the maximum sum    int sum = 0;    for (int i = 0; i < N; i++) {         // If B[i] is equal to 0        if (pairs[i].second == 0) {             // Simply add A[i] to the sum            sum += pairs[i].first;        }         else if (pairs[i].second == 1) {             // Add the highest K numbers            if (K > 0) {                sum += pairs[i].first;                K--;            }             // Subtract from the sum            else {                sum -= pairs[i].first;            }        }    }     // Return the sum    return sum;} // Driver Codeint 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 << maximizeScore(A, B, K, N);    return 0;}
// Java program to maximise the// sum of the given arrayimport java.util.*; class Pairs implements Comparable<Pairs>{    int first, second;    Pairs(int x, int y)    {        first = x;        second = y;    }    public int compareTo(Pairs p)    {        return p.first - first;    }} class GFG{     // Function to maximise the sum of// the given arraystatic int maximiseScore(int A[], int B[],                         int K, int N){     // Stores {A[i], B[i]} pairs    ArrayList<Pairs> pairs = new ArrayList<>();    for(int i = 0; i < N; i++)    {        pairs.add(new Pairs(A[i], B[i]));    }     // Sort in descending order of the    // values in the array A[]    Collections.sort(pairs);     // Stores the maximum sum    int sum = 0;    for(int i = 0; i < N; i++)    {                 // If B[i] is equal to 0        if (pairs.get(i).second == 0)        {                         // Simply add A[i] to the sum            sum += pairs.get(i).first;        }         else if (pairs.get(i).second == 1)        {                         // Add the highest K numbers            if (K > 0)            {                sum += pairs.get(i).first;                K--;            }             // Subtract from the sum            else            {                sum -= pairs.get(i).first;            }        }    }     // Return the sum    return sum;} // Driver Codepublic 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));}} // This code is contributed by jrishabh99
# Python Program to maximise the# sum of the given array # Comparator to sort the array# in ascending orderdef compare(p1, p2):    return p1[0] > p2[0] # Function to maximise the sum of# the given arraydef maximiseScore(A, B, K, N):         # Stores {A[i], B[i]} pairs    pairs = []    for i in range(N):        pairs.append([A[i], B[i]])         # Sort in descending order of the    # values in the array A[]    pairs.sort(key = lambda x:x[0], reverse = True)     # Stores the maximum sum    Sum = 0     for i in range(N):               # If B[i] is equal to 0        if(pairs[i][1] == 0):                       # Simply add A[i] to the sum            Sum += pairs[i][0]        elif(pairs[i][1] == 1):                         # Add the highest K numbers            if(K > 0):                Sum += pairs[i][0]                K -= 1                             # Subtract from the sum            else:                Sum -= pairs[i][0]         # Return the sum    return Sum # Driver CodeA = [5, 4, 6, 2, 8]B = [1, 0, 1, 1, 0]K = 2N = len(A)print(maximiseScore(A, B, K, N)) # This code is contributed by avanitrachhadiya2155
<script> // JavaScript Program to maximize the// sum of the given array // Comparator to sort the array// in ascending orderfunction compare(p1,p2){    return p2[0] - p1[0];} // Function to maximize the sum of// the given arrayfunction maximizeScore(A, B, K, N){     // Stores {A[i], B[i]} pairs    let pairs = new Array(N);    for (let i = 0; i < N; i++) {        pairs[i] = [A[i], B[i]];    }     // Sort in descending order of the    // values in the array A[]    pairs.sort(compare);     // Stores the maximum sum    let sum = 0;    for (let i = 0; i < N; i++) {         // If B[i] is equal to 0        if (pairs[i][1] == 0) {             // Simply add A[i] to the sum            sum += pairs[i][0];        }         else if (pairs[i][1] == 1) {             // Add the highest K numbers            if (K > 0) {                sum += pairs[i][0];                K--;            }             // Subtract from the sum            else {                sum -= pairs[i][0];            }        }    }     // Return the sum    return sum;} // Driver Codelet A = [ 5, 4, 6, 2, 8 ];let B = [ 1, 0, 1, 1, 0 ];let K = 2;let N = A.length;document.write(maximizeScore(A, B, K, N),"</br>"); // This code is contributed by shinjanpatra.</script>
21
 
Time complexity: O(N*log(N))Auxiliary Space: O(N) 
jrishabh99
avanitrachhadiya2155
chhabradhanvi
shinjanpatra
Arrays
Greedy
Mathematical
Sorting
Arrays
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string