[LeetCode] Minimum Increment to Make Array Unique

945. Minimum Increment to Make Array Unique

You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.

Return the minimum number of moves to make every value in nums unique.

The test cases are generated so that the answer fits in a 32-bit integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
int res = 0, n = A.size();
sort(begin(A), end(A));
for(int i = 1; i < n; i++) {
if(A[i] > A[i-1]) continue;
res += A[i-1] + 1 - A[i];
A[i] = A[i-1] + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/20/PS/LeetCode/minimum-increment-to-make-array-unique/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.