Advertisement
praveenpkg8

*Minimum operations required

Jul 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. /*Minimum operations required to make all the elements distinct in an array
  2. Given an array of N integers. If a number occurs more than once, choose any number y from the array and replace the x in the array to x+y such that x+y is not in the array. The task is to find the minimum number of operations to make the array a distinct one.
  3.  
  4. Examples:
  5.  
  6. Input: a[] = {2, 1, 2}
  7. Output: 1
  8. Let x = 2, y = 1 then replace 2 by 3.
  9. Performing the above step makes all the elements in the array distinct.
  10.  
  11. Input: a[] = {1, 2, 3}
  12. Output: 0
  13.  
  14. Recommended: Please try your approach on {IDE} first, before moving on to the solution.
  15.  
  16.  
  17. Approach: If a number appears more than once, then the summation of (occurrences-1) for all duplicate elements will be the answer. The main logic behind this is if x is replaced by x+y where y is the largest element in the array, then x is replaced by x+y which is the largest element in the array. Use a map to store the frequency of the numbers of array. Traverse in the map, and if the frequency of an element is more than 1, add it to the count by subtracting one.
  18.  
  19. Below is the implementation of the above approach:*/
  20.  
  21. // C++ program to find Minimum number
  22. // of  changes to make array distinct
  23. #include <bits/stdc++.h>
  24. using namespace std;
  25.  
  26. // Fucntion that returns minimum number of changes
  27. int minimumOperations(int a[], int n)
  28. {
  29.  
  30.     // Hash-table to store frequency
  31.     unordered_map<int, int> mp;
  32.  
  33.     // Increase the frequency of elements
  34.     for (int i = 0; i < n; i++)
  35.         mp[a[i]] += 1;
  36.  
  37.     int count = 0;
  38.  
  39.     // Traverse in the map to sum up the (occurences-1)
  40.     // of duplicate elements
  41.     for (auto it = mp.begin(); it != mp.end(); it++) {
  42.         if ((*it).second > 1)
  43.             count += (*it).second-1;
  44.     }
  45.     return count;
  46. }
  47.  
  48. // Driver Code
  49. int main()
  50. {
  51.     int a[] = { 2, 1, 2, 3, 3, 4, 3 };
  52.     int n = sizeof(a) / sizeof(a[0]);
  53.  
  54.     cout << minimumOperations(a, n);
  55.     return 0;
  56. }
  57. /*Run on IDE
  58. Output:
  59. 3
  60. Time Complexity: O(N)*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement