![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to find the minimum cost required to convert a given array into a permutation from 1 to M (where M can be any positive value) by performing the following operations:
Examples:
Input: arr = { 2, 1, 3, 6, 7 }, X = 2, Y = 3
Output: 4
Explanation: Remove the number 6 and 7 from the array that take 2 + 2 cost.Input: arr = { 2, 3, 6, 3, 5 }, X = 3, Y =7
Output: 16
Explanation: Remove the number 3, 5, 6 that take cost 3 + 3 + 3 = 9 and add number 1 take cost 7. So total cost = 9 + 7.
Approach: To solve the problem follow the below idea:
Initially keep the distinct values in a temporary array (say temp[] of size M), sort the array and traverse from left. Consider, we want the permutation to have values from 1 to the value of ith index. Consider the cost required in this manner for each index and the minimum of them will be required answer.
So, the cost for ith index will be (M - i - 1)*X + (temp[i] - (i + 1)) * Y because we have to remove (M - (i + 1)) elements and insert (temp[i] -(i+1)) new elements.
Illustration:
For a better understanding, follow the below illustration:
Consider arr[] = { 2, 3, 6, 3, 5 }, X = 3, Y =7
First create an array with only distinct elements temp[] and sort it. So temp[] will be {2, 3, 5, 6}. So initially we have already taken a cost of 3 to remove the duplicate
Index 0: Remove all numbers after index 0, it takes cost 3 * 3 for remove and add [2 - (0+1)] = 1 new element (i.e., 1 itself) which takes cost 1*7. So total cost = 9 + 7 + 3 = 16 .
Index 1: At index 1, remove all numbers after index 1. It takes cost 2 * 3 for remove and add [3 - (1 + 1)] = 1 new element which takes cost 1*7. So total cost = 6 + 7 = 13.
Index 2: At index 2, remove all numbers after index 2. It takes cost 1 * 3 for remove and add [5 - (2 + 1)] = 2 new elements which takes cost = 2* 7. So total cost = 3 + 14 = 17.
Index 3: At index 3, remove all numbers after index 3. It takes no cost. Add [6 - (3 + 1)] = 2 new elements which takes cost 2*7. So total cost = 2 + 14 = 16.
So minimum cost = 13 + 3 = 16.
Below are the steps to implement the above idea:
Below is the implementation of the above approach.
16
Time Complexity: O(N * logN)
Auxiliary Space: O(N)