Open In App

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

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Output

53

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads