Skip to content
Related Articles

Related Articles

Minimize cost to make given Array a permutation of 1 to N by given replacements

Improve Article
Save Article
  • Last Updated : 09 Feb, 2022
Improve Article
Save Article

Given two arrays a[] and b[] of length N and an integer K (1 ≤ K ≤ N). All the integers in array a[] lie within the range [1, K]. ith value in array b[] denotes the cost of replacing a[i] with any number in the range [1, N]. The task is to find the minimum cost to replace the elements of array a[] to turn it into a permutation of 1 to N.

Note: A permutation of 1 to N contains all the values from 1 to N in any order and no value is repeated.

Examples:

Input: K = 7, a[] = {1, 1, 3, 4, 5, 3, 7, 1}
b[] = {7, 5, 4, 8, 1, 3, 5, 2}
Output: 10
Explanation: In a[] some numbers are repeating which are 1, 1, 3, 3, 1.
Now, make two 1’s and one 3 unique.
Select a[1], a[5] and a[7] and replace them with 2, 6, and 8 to make array a permutation of 1 to 8.
The total cost is b[1] + b[5] + b[7] = 5 + 3 + 2 = 10.
This is the minimum cost to make a[] a permutation of 1 to 8.
Now, a[] becomes {1, 2, 3, 4, 5, 6, 7, 8}

Input: K = 3, a[] = {3, 1, 2}
b[] = {5, 3, 4}
Output: 0
Explanation: a[] is already a permutation of 1 to 3. So no need to replace any value.

 

Approach: The solution of the problem is based on the concept of hashing. Store the elements which are repeating and replace all but the one having the maximum cost for replacement. Follow the steps mentioned below to solve the problem:

  • Initialize the map to store a[i] and b[i].
  • Initialize vector to store the minimum answer.
  • Now traverse both the arrays.
    • If a[i] is not present in the map, store a[i] as key and b[i] as a value in the map.
    • Else if a[i] is present and the value of a[i] stored in the map is less than b[i], store the existing value of a[i] in a vector v and change the value in map to b[i].
    • Else store b[i] in the vector v.
  • Sort the vector v.
  • Initialize the variable ans = 0.
  • Now traverse vector (K – size of map) times and sum all the values of vector in ans.

Below is the implementation of the above approach. 

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the minimum cost
int minCost(int a[], int b[], int N, int K)
{
    // Initialize map and vector
    map<int, int> m;
    vector<int> v;
 
    for (int i = 0; i < N; i++) {
        if (m[a[i]] == 0) {
            m[a[i]] = b[i];
        }
        else {
            if (m[a[i]] < b[i]) {
                v.push_back(m[a[i]]);
                m[a[i]] = b[i];
            }
            else {
                v.push_back(b[i]);
            }
        }
    }
    sort(v.begin(), v.end());
    int size = K - m.size();
    int ans = 0;
    for (int i = 0; i < size; i++) {
        ans += v[i];
    }
    return ans;
}
 
// Driver code
int main()
{
    int a[] = { 1, 1, 3, 1, 5, 3, 7, 1 };
    int b[] = { 5, 7, 4, 8, 1, 3, 5, 2 };
    int K = 7;
    int N = sizeof(a) / sizeof(a[0]);
     
    cout << minCost(a, b, N, K);
    return 0;
}


Java




// JAVA code to implement the approach
import java.util.*;
class GFG
{
 
  // Function to calculate the minimum cost
  public static int minCost(int[] a, int[] b, int N,
                            int K)
  {
 
    // Initialize map and ArrayList
    HashMap<Integer, Integer> m
      = new HashMap<Integer, Integer>();
    ArrayList<Integer> v = new ArrayList<Integer>();
 
    for (int i = 0; i < N; i++) {
      if (m.containsKey(a[i])) {
        m.put(a[i], 0);
      }
    }
    for (int i = 0; i < N; i++) {
      if (m.get(a[i]) == null) {
        m.put(a[i], b[i]);
      }
      else {
        if (m.get(a[i]) < b[i]) {
          v.add(m.get(a[i]));
          m.put(a[i], b[i]);
        }
        else {
          v.add(b[i]);
        }
      }
    }
    Collections.sort(v);
    int size = K - m.size();
    int ans = 0;
    for (int i = 0; i < size; i++) {
      ans += v.get(i);
    }
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] a = new int[] { 1, 1, 3, 1, 5, 3, 7, 1 };
    int[] b = new int[] { 5, 7, 4, 8, 1, 3, 5, 2 };
    int K = 7;
    int N = a.length;
 
    System.out.print(minCost(a, b, N, K));
  }
}
 
// This code is contributed by Taranpreet


C#




// C# code to implement the approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to calculate the minimum cost
  static int minCost(int []a, int []b, int N, int K)
  {
 
    // Initialize map and vector
    Dictionary<int, int> m =
      new Dictionary<int, int>();
    ArrayList v = new ArrayList();
 
    for(int i = 0; i < N; i++) {
      if(!m.ContainsKey(a[i])) {
        m.Add(a[i], 0);
      }
    }
 
    for (int i = 0; i < N; i++) {
      if (m[a[i]] == 0) {
        m[a[i]] = b[i];
      }
      else {
        if (m[a[i]] < b[i]) {
          v.Add(m[a[i]]);
          m[a[i]] = b[i];
        }
        else {
          v.Add(b[i]);
        }
      }
    }
    v.Sort();
    int size = K - m.Count;
    int ans = 0;
    for (int i = 0; i < size; i++) {
      ans += (int)v[i];
    }
    return ans;
  }
 
  // Driver code
  public static void Main()
  {
    int []a = { 1, 1, 3, 1, 5, 3, 7, 1 };
    int []b = { 5, 7, 4, 8, 1, 3, 5, 2 };
    int K = 7;
    int N = a.Length;
 
    Console.Write(minCost(a, b, N, K));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
      // JavaScript code for the above approach
 
      // Function to calculate the minimum cost
      function minCost(a, b, N, K) {
          // Initialize map and vector
          let m = new Map();
          let v = [];
 
          for (let i = 0; i < N; i++) {
              if (m.has(a[i]) == false) {
                  m.set(a[i], b[i]);
              }
              else {
                  if (m.get(a[i]) < b[i]) {
                      v.push(m.get(a[i]));
                      m.set(a[i], b[i]);
                  }
                  else {
                      v.push(b[i]);
                  }
              }
          }
          v.sort(function (a, b) { return a - b })
          let size = K - m.size;
          let ans = 0;
          for (let i = 0; i < size; i++) {
              ans += v[i];
          }
          return ans;
      }
 
      // Driver code
 
      let a = [1, 1, 3, 1, 5, 3, 7, 1];
      let b = [5, 7, 4, 8, 1, 3, 5, 2];
      let K = 7;
      let N = a.length;
 
      document.write(minCost(a, b, N, K));
 
     // This code is contributed by Potta Lokesh
  </script>


Python3




# Python code for the above approach
 
# Function to calculate the minimum cost
def minCost(a, b, N, K):
    # Initialize map and vector
    m = {}
    v = [];
 
    for  i in range(N):
        if (a[i] not in m):
            m[a[i]] = b[i]
         
        else:
            if (m[a[i]] < b[i]):
                v.append(m[a[i]]);
                m[a[i]] = b[i]
             
            else:
                v.append(b[i]);
 
    v.sort()
    size = K - len(m);
    ans = 0;
    for i in range(size):
        ans += v[i];
    return ans;
 
 
# Driver code
 
a = [1, 1, 3, 1, 5, 3, 7, 1];
b = [5, 7, 4, 8, 1, 3, 5, 2];
K = 7;
N = len(a)
 
print(minCost(a, b, N, K));
 
# This code is contributed by Saurabh Jaiswal


 
 

Output

10

 

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

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!