Skip to content
Related Articles

Related Articles

Improve Article

Maximize the Sum of the given array using given operations

  • Last Updated : 17 Dec, 2020

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 = 21
Input: 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++




// C++ Program to maximise the
// sum of the given array
#include <bits/stdc++.h>
using namespace std;
 
// Comparator to sort the array
// in ascending order
bool compare(pair<int, int> p1,
             pair<int, int> p2)
{
    return p1.first > p2.first;
}
 
// Function to maximise the sum of
// the given array
int maximiseScore(int A[], int B[],
                  int K, int N)
{
 
    // Stores {A[i], B[i]} pairs
    vector<pair<int, int> > pairs(N);
    for (int i = 0; i < N; i++) {
        pairs[i] = make_pair(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 Code
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;
}

Java




// Java program to maximise the
// sum of the given array
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{
     
// Function to maximise the sum of
// the given array
static int maximiseScore(int A[], int B[],
                         int K, int N)
{
 
    // Stores {A[i], B[i]} pairs
    ArrayList<Pair> pairs = new ArrayList<>();
    for(int i = 0; i < N; i++)
    {
        pairs.add(new Pair(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 Code
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));
}
}
 
// This code is contributed by jrishabh99

Python3




# Python Program to maximise the
# sum of the given array
 
# Comparator to sort the array
# in ascending order
def compare(p1, p2):
    return p1[0] > p2[0]
 
# Function to maximise the sum of
# the given array
def 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 Code
A = [5, 4, 6, 2, 8]
B = [1, 0, 1, 1, 0]
K = 2
N = len(A)
print(maximiseScore(A, B, K, N))
 
# This code is contributed by avanitrachhadiya2155
Output: 
21

 

Time complexity: O(N*log(N))
Auxiliary Space: O(N) 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :