Minimum Increment to Make Array Unique in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers A, here a move consists of choosing any A[i], and incrementing it by 1. We have to find the least number of moves to make every value in A unique. So if the input is like [3,2,1,2,1,7], then the output will be 6, as after 6 moves, the array could be [3,4,1,2,5,7], it can be shown with 5 or less moves that it is impossible for the array to have all distinct values.

To solve this, we will follow these steps −

  • ret:= 0

  • sort array A

  • create one set called visited to keep track which value is considered before

  • for i in range 1 to size of array A – 1

    • if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1

  • return ret.

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minIncrementForUnique(vector<int>& A) {
      int ret = 0;
      sort(A.begin(), A.end());
      set <int> visited;
      for(int i = 1; i < A.size(); i++){
         if(A[i] <= A[i - 1]){
            ret+= (A[i - 1] + 1) - A[i];
            A[i] = A[i - 1] + 1;
         }
      }
      return ret;
   }
};
main(){
   vector<int> v1 = {3,2,1,2,1,7};
   Solution ob;
   cout << (ob.minIncrementForUnique(v1));
}

Input

[3,2,1,2,1,7]

Output

6
raja
Published on 10-Apr-2020 10:13:29
Advertisements