Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximize the sum of modified values after rearranging given array based on condition array

  • Last Updated : 26 Oct, 2021

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:

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.

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

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>
Output
53

Time Complexity: O(N*log N)
Space Complexity: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!