forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimumDeletionsToMakeArrayDivisible.java
83 lines (66 loc) · 1.92 KB
/
MinimumDeletionsToMakeArrayDivisible.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Solution {
public int minOperations(int[] nums, int[] numsDivide) {
int gcd = findGCD(numsDivide);
Arrays.sort(nums);
// smallest to largest
for (int i = 0; i < nums.length; i++) {
if (gcd % nums[i] == 0)
return i;
}
return -1;
}
private int findGCD(int[] numsDivide){
int gcd = numsDivide[0];
for (int i=1;i<numsDivide.length;i++){
int num = numsDivide[i];
while (num > 0) {
int tmp = gcd % num;
gcd = num;
num = tmp;
}
}
return gcd;
}
}
// https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/
// @author: anuj0503
class Solution {
public int minOperations(int[] nums, int[] numsDivide) {
int gcd = numsDivide[0];
if(numsDivide.length != 1)
gcd = findGCD(numsDivide, numsDivide.length);
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int i = 0; i < nums.length; i++){
map.putIfAbsent(nums[i], 0);
map.put(nums[i], map.get(nums[i]) + 1);
}
int result = 0;
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
int key = entry.getKey();
int val = entry.getValue();
if(gcd%key == 0){
return result;
}
result += val;
}
return -1;
}
private int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
private int findGCD(int arr[], int n)
{
int result = arr[0];
for (int element: arr){
result = gcd(result, element);
if(result == 1)
{
return 1;
}
}
return result;
}
}