-
Notifications
You must be signed in to change notification settings - Fork 0
/
Make array elements unique
54 lines (43 loc) · 1.25 KB
/
Make array elements unique
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//Make array elements unique
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
String arr[] = br.readLine().split(" ");
int a[] = new int[arr.length];
for(int i = 0; i < arr.length; i++) {
a[i] = Integer.parseInt(arr[i]);
}
Solution obj = new Solution();
int f = 0;
int A = obj.minIncrements(a);
System.out.println(A);
}
}
}
class Solution {
public int minIncrements(int[] arr) {
int n = arr.length;
int count = 0;
int mx = arr[0];
for(int ele : arr) {
mx = Math.max(mx, ele);
}
int[] freq = new int[n + mx];
for(int ele : arr) {
freq[ele]++;
}
for(int num = 0; num < freq.length; num++) {
if(freq[num] > 1) {
freq[num + 1] += freq[num] - 1;
count += freq[num] - 1;
freq[num] = 1;
}
}
return count;
}
}