Skip to content

945. Minimum Increment to Make Array Unique 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int minIncrementForUnique(vector<int>& A) {
    int ans = 0;
    int minAvailable = 0;

    sort(begin(A), end(A));

    for (int a : A) {
      ans += max(minAvailable - a, 0);
      minAvailable = max(minAvailable, a) + 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int minIncrementForUnique(int[] A) {
    int ans = 0;
    int minAvailable = 0;

    Arrays.sort(A);

    for (int a : A) {
      ans += Math.max(minAvailable - a, 0);
      minAvailable = Math.max(minAvailable, a) + 1;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def minIncrementForUnique(self, A: List[int]) -> int:
    ans = 0
    minAvailable = 0

    A.sort()

    for a in A:
      ans += max(minAvailable - a, 0)
      minAvailable = max(minAvailable, a) + 1

    return ans