Maximize the Sum of the given array using given operations
Last Updated :
05 Oct, 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 = 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 maximize the
// sum of the given array
#include <bits/stdc++.h>
using namespace std;
// Comparator to sort the array
// in ascending order
bool compare(pairs<int, int> p1,
pairs<int, int> p2)
{
return p1.first > p2.first;
}
// Function to maximize the sum of
// the given array
int 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 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 << maximizeScore(A, B, K, N);
return 0;
}
Java
// Java program to maximise the
// sum of the given array
import 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 array
static 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 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
C#
// C# program to maximise the
// sum of the given array
using System;
using System.Collections;
using System.Collections.Generic;
class Pairs : IComparable
{
public int first, second;
public Pairs(int x, int y)
{
first = x;
second = y;
}
public int CompareTo(object obj)
{
if (obj == null)
return 1;
Pairs p = obj as Pairs;
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
List<Pairs> pairs = new List<Pairs>();
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[]
pairs.Sort();
// 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
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;
Console.Write(maximiseScore(A, B, K, N));
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript Program to maximize the
// sum of the given array
// Comparator to sort the array
// in ascending order
function compare(p1,p2)
{
return p2[0] - p1[0];
}
// Function to maximize the sum of
// the given array
function 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 Code
let 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>
Time complexity: O(N*log(N))
Auxiliary Space: O(N)
Similar Reads
Find the Maximum sum of the Array by performing the given operations Given an Array A[] of size N with repeated elements and all array elements are positive, the task is to find the maximum sum by applying the given operations: Select any 2 indexes and select 2 integers(say x and y) such that the product of the elements(x and y) is equal to the product of the element
5 min read
Maximizing array sum with given operation There is an array consisting of (2 * n - 1) integers. We can change sign of exactly n elements in the array. In other words, we can select exactly n array elements, and multiply each of them by -1. Find the maximum sum of the array. Examples : Input : arr[] = 50 50 50 Output : 150 There is no need t
6 min read
Maximize the sum of sum of the Array by removing end elements Given an array arr of size N, the task is to maximize the sum of sum, of the remaining elements in the array, by removing the end elements.Example: Input: arr[] = {2, 3} Output: 3 Explanation: At first we will delete 2, then sum of remaining elements = 3. Then delete 3. Therefore sum of sum = 3 + 0
6 min read
Maximize sum of pairwise products generated from the given Arrays Given three arrays arr1[], arr2[] and arr3[] of length N1, N2, and N3 respectively, the task is to find the maximum sum possible by adding the products of pairs taken from different arrays. Note: Each array element can be a part of a single pair. Examples: Input: arr1[] = {3, 5}, arr2[] = {2, 1}, ar
11 min read
Remove array end element to maximize the sum of product Given an array of N positive integers. We are allowed to remove element from either of the two ends i.e from the left side or right side of the array. Each time we remove an element, score is increased by value of element * (number of element already removed + 1). The task is to find the maximum sco
9 min read
Perform K of Q queries to maximize the sum of the array elements Given an array arr[] of N integers and an integer K. Also given are Q queries which have two numbers L and R. For every query, you can increase all the elements of the array in the index range [L, R] by 1. The task is to choose exactly K queries out of Q queries such that the sum of the array at the
7 min read
Maximize the first element of the array such that average remains constant Given an array arr[] of length N and an integer X, the task is to find the maximum value R of updated first element such that the average of the array remains constant and no elements of the array should become negative. The maximum value of the first element should be in the range arr[0] <= R
6 min read
Minimum possible sum of array elements after performing the given operation Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
9 min read
Maximum Sum of Array with given MEX Given 3 integers N, K, and X, the task is to construct an array arr[] with the below conditions: Size of the array = NMEX of the array = KAll array elements should be at most XAmong all the array that follows the above condition print the one having the maximum sum of its elements or print -1 if no
7 min read
Maximum possible array sum after performing the given operation Given an array arr[] of size N, the task is to find the maximum sum of the elements of the array after applying the given operation any number of times. In a single operation, choose an index 1 ? i < N and multiply both arr[i] and arr[i - 1] by -1.Examples: Input: arr[] = {-10, 5, -4} Output: 19
9 min read