Maximize the sum of modified values after rearranging given array based on condition array
Last Updated :
24 Jan, 2023
Given a binary array arr1[] and an integer array arr2[], each of length N, the task is to rearrange the elements in the array arr2 such that the total cost generated is maximized. The total cost generated is calculated by summation of modified values in the arr2 array. The values are modified in such a way that an integer corresponding to the value 0 in the arr1 array has no effect on the other elements but an integer corresponding to value 1 in the arr1 array can double the value of the next integer.
Examples:
Input: N = 2, arr1 = [1, 0], arr2 = [3, 4]
Output: 11
Explanation: Element 3 corresponds to value 1 so it can double the value of the next element. Out of 2 arrangements possible [3, 4] and [4, 3] so in the 1st case cost generated is 3+4*2 = 11 and in the 2nd case the cost generated is 4+3=7
Input: N = 5, arr1 = [1, 0, 1, 0, 1], arr2 = [3, 7, 2, 12, 5]
Output: 53
Explanation: Maximum cost can be generated in the arrangement [3, 7, 2, 5, 12] here 1st, 3rd and 4th elements correspond to value 1 and hence their next elements cost can be doubled so cost is 3+7*2+2+5*2+12*2=53
Approach: Given problem can be solved by using the greedy approach. The idea is to sort the array in descending order then iterate it to calculate the cost generated. Below steps can be followed:
- Initialize an auxiliary array arr1 and copy all elements of arrayarr2 into it, which have corresponding value 1 in the array arr1
- Find the min value in the array arr1, remove it from the array and store it in a variable, say val
- Sort the array arr2 in descending order
- Initialize a variable ans to calculate the maximum cost generated
- If all elements in the array arr1 are 1 then double the value of all elements except the min value val and return their sum
- Else add double the value of arr1 elements into ans, and rest all elements without modification
C++
// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to compute maximum power
int max_pow(vector<int>& arr1, vector<int>& arr2)
{
// Count of 1 in arr1
int cnt = count(arr1.begin(), arr1.end(), 1);
// Keep an array of integers corresponding
// to value 1 in arr1 to eliminate the
// integers contributing to minimum cost
vector<int> cost1;
for (int i = 0; i < arr1.size(); ++i) {
if (arr1[i] == 1)
cost1.push_back(arr2[i]);
}
int val = cost1[0];
for (int i = 1; i < cost1.size(); ++i) {
val = min(val, cost1[i]);
}
// Delete the minimum cost
arr2.erase(find(arr2.begin(), arr2.end(), val));
sort(arr2.rbegin(), arr2.rend());
// Ans for storing max result
int ans = 0;
// Case when all are of type 1
if (arr2.size() == cnt - 1) {
int sum = 0;
for (auto it : arr2) {
sum += it;
}
ans = sum * 2 + val;
}
else {
int sum = 0;
for (auto it : arr2) {
sum += it;
}
for (int i = 0; i < cnt; ++i) {
sum += arr2[i];
}
ans = val + sum;
}
return ans;
}
// Driver code
int main()
{
int N = 5;
vector<int> arr_type = { 1, 0, 1, 0, 1 };
vector<int> arr_power = { 3, 2, 7, 12, 5 };
cout << max_pow(arr_type, arr_power);
return 0;
}
// This code is contributed by rakeshsahni
Java
// java code to implement the above approach
import java.io.*;
import java.util.*;
import java.util.ArrayList;
class GFG
{
// Function to find pair satisfying the condition
public static int max_pow(ArrayList<Integer> arr1, ArrayList<Integer> arr2)
{
// Count of 1 in arr1
int cnt = 0;
for(int i = 0; i < arr1.size(); i++)
{
if(arr1.get(i)==1)
cnt++;
}
// Keep an array of integers corresponding
// to value 1 in arr1 to eliminate the
// integers contributing to minimum cost
ArrayList<Integer> cost1 = new ArrayList<Integer>();
for (int i = 0; i < arr1.size(); ++i) {
if (arr1.get(i) == 1)
cost1.add(arr2.get(i));
}
int val = cost1.get(0);
for (int i = 1; i < cost1.size(); ++i) {
val = Math.min(val, cost1.get(i));
}
// Delete the minimum cost
arr2.remove(arr2.indexOf(val));
Collections.sort(arr2,Collections.reverseOrder());
// Ans for storing max result
int ans = 0;
// Case when all are of type 1
if (arr2.size() == cnt - 1) {
int sum = 0;
for (int i=0;i<arr2.size();i++) {
sum += arr2.get(i);
}
ans = sum * 2 + val;
}
else {
int sum = 0;
for (int i=0;i<arr2.size();i++) {
sum += arr2.get(i);
}
for (int i = 0; i < cnt; i++) {
sum += arr2.get(i);
}
ans = val + sum;
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
ArrayList<Integer> arr_type = new ArrayList<>(List.of(1,0,1,0,1));
ArrayList<Integer> arr_power = new ArrayList<>(List.of(3,2,7,12,5));
System.out.println(max_pow(arr_type, arr_power));
}
}
// This code is contributed by Aditya Patil
Python3
# Python implementation for the above approach
# Function to compute maximum power
def max_pow(arr1, arr2):
# Count of 1 in arr1
count = arr1.count(1)
# Keep an array of integers corresponding
# to value 1 in arr1 to eliminate the
# integers contributing to minimum cost
cost1 = []
for i in range(len(arr1)):
if(arr1[i] == 1):
cost1.append(arr2[i])
val = min(cost1)
# Delete the minimum cost
del arr2[arr2.index(val)]
arr2.sort(reverse = True)
# Ans for storing max result
ans = 0
# Case when all are of type 1
if(len(arr2) == count-1):
ans = sum(arr2)*2 + val
else:
ans = val + sum(arr2)+sum(arr2[:count])
return ans
# Driver code
N = 5
arr_type = [1, 0, 1, 0, 1]
arr_power = [3, 2, 7, 12, 5]
print(max_pow(arr_type, arr_power))
JavaScript
<script>
// JavaScript implementation for the above approach
// Function to compute maximum power
function removeSmallest(arr1, arr2)
{
var min = Math.min(...arr1);
return arr2.filter(e => e != min);
}
function add(accumulator, a) {
return accumulator + a;
}
function max_pow(arr1, arr2){
// Count of 1 in arr1
let count = 0
arr1.forEach(e=>{if(e == 1)
count += 1
})
// Keep an array of integers corresponding
// to value 1 in arr1 to eliminate the
// integers contributing to minimum cost
let cost1 = []
let i = 0
arr1.forEach(e=>{if(e == 1){
cost1.push(arr2[i])
}
i += 1
})
let val = Math.min(...cost1)
// Delete the minimum cost
arr2 = removeSmallest(cost1,arr2)
arr2.sort(function(a, b){return a - b})
arr2.reverse()
// Ans for storing max result
let ans = 0
// Case when all are of type 1
if(arr2.length == count-1)
ans = (arr2.reduce(add,0))*2 + val
else
ans = val + arr2.reduce(add,0)+(arr2.slice(0,count)).reduce(add,0)
return ans
}
// Driver code
let N = 5
let arr_type = [1, 0, 1, 0, 1]
let arr_power = [3, 2, 7, 12, 5]
document.write(max_pow(arr_type, arr_power))
// This code is contributed by rohitsingh07052.
</script>
C#
// C# code to implement the above approach
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
// Function to find pair satisfying the condition
public static int max_pow(List<int> arr1, List<int> arr2)
{
// Count of 1 in arr1
int cnt = 0;
for(int i = 0; i < arr1.Count; i++)
{
if(arr1[i]==1)
cnt++;
}
// Keep an array of integers corresponding
// to value 1 in arr1 to eliminate the
// integers contributing to minimum cost
List<int> cost1 = new List<int>();
for (int i = 0; i < arr1.Count; ++i) {
if (arr1[i] == 1)
cost1.Add(arr2[i]);
}
int val = cost1.Min();
// Delete the minimum cost
arr2.Remove(val);
arr2.Sort((a,b) => b.CompareTo(a));
// ans for storing max result
int ans = 0;
// Case when all are of type 1
if (arr2.Count == cnt - 1) {
int sum = 0;
for (int i=0;i<arr2.Count;i++) {
sum += arr2[i];
}
ans = sum * 2 + val;
}
else {
int sum = 0;
for (int i=0;i<arr2.Count;i++) {
sum += arr2[i];
}
for (int i = 0; i < cnt; i++) {
sum += arr2[i];
}
ans = val + sum;
}
return ans;
}
// Driver Code
static void Main(string[] args)
{
int N = 5;
List<int> arr_type = new List<int>() { 1, 0, 1, 0, 1 };
List<int> arr_power = new List<int>() { 3, 2, 7, 12, 5 };
Console.WriteLine(max_pow(arr_type, arr_power));
}
}
// This code is contributed by Harshad
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Similar Reads
Rearrange array elements to maximize the sum of MEX of all prefix arrays Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximize sum of given array after removing valleys Given an array arr[] of integers of size N, the task is to maximize the sum of the array after removing valleys from the array when only reducing the value of an element is allowed i.e. the new formed array should not contain any element which has greater value after modification. Valleys:- An index
9 min read
Maximize Array sum by adding multiple of another Array element in given ranges Given two arrays X[] and Y[] of length N along with Q queries each of type [L, R] that denotes the subarray of X[] from L to R. The task is to find the maximum sum that can be obtained by applying the following operation for each query: Choose an element from Y[]. Add multiples with alternate +ve an
15+ min read
Rearrange an array to maximize sum of Bitwise AND of same-indexed elements with another array Given two arrays A[] and B[] of sizes N, the task is to find the maximum sum of Bitwise AND of same-indexed elements in the arrays A[] and B[] that can be obtained by rearranging the array B[] in any order. Examples: Input: A[] = {1, 2, 3, 4}, B[] = {3, 4, 1, 2}Output: 10Explanation: One possible wa
15 min read
Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1 Given an array arr[] consisting of N positive integers, the task is to maximize the sum of the array element such that the first element of the array is 1 and the difference between the adjacent elements of the array is at most 1 after performing the following operations: Rearrange the array element
7 min read
Maximum sum after rearranging the array for K queries Given two arrays arr[] containing N integers and Q[][] containing K queries where every query represents a range [L, R]. The task is to rearrange the array and find the maximum possible sum of all the subarrays where each subarray is defined by the elements of the array in the range [L, R] given by
10 min read