You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.
Return _theminimum number of deletions such that the smallest element in _nums _divides all the elements of _numsDivide. If this is not possible, return -1.
Input: nums =[2,3,2,4,3], numsDivide =[9,6,9,3,15]Output: 2Explanation: After deleting two elements, nums =[3,3,3].3 divides all elements in numsDivide.
To make the smallest element in nums divide all elements in numsDivide, it must divide the GCD of numsDivide. We sort nums and try each element in increasing order, counting deletions until we find one that divides the GCD.
classSolution {
public:int minDeletions(vector<int>& nums, vector<int>& numsDivide) {
int g = numsDivide[0];
for (int x : numsDivide) g = gcd(g, x);
sort(nums.begin(), nums.end());
for (int i =0; i < nums.size(); ++i) {
if (g % nums[i] ==0) return i;
}
return-1;
}
intgcd(int a, int b) {
return b ==0? a : gcd(b, a % b);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcgcd(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna}
funcminDeletions(nums, numsDivide []int) int {
g:=numsDivide[0]
for_, x:=rangenumsDivide { g = gcd(g, x) }
sort.Ints(nums)
fori, x:=rangenums {
ifg%x==0 { returni }
}
return-1}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintminDeletions(int[] nums, int[] numsDivide) {
int g = numsDivide[0];
for (int x : numsDivide) g = gcd(g, x);
Arrays.sort(nums);
for (int i = 0; i < nums.length; ++i) {
if (g % nums[i]== 0) return i;
}
return-1;
}
intgcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminDeletions(nums: IntArray, numsDivide: IntArray): Int {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
var g = numsDivide[0]
for (x in numsDivide) g = gcd(g, x)
nums.sort()
for ((i, x) in nums.withIndex()) {
if (g % x ==0) return i
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defminDeletions(self, nums: list[int], numsDivide: list[int]) -> int:
from math import gcd
from functools import reduce
g = reduce(gcd, numsDivide)
nums.sort()
for i, x in enumerate(nums):
if g % x ==0:
return i
return-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnmin_deletions(nums: Vec<i32>, nums_divide: Vec<i32>) -> i32 {
fngcd(a: i32, b: i32) -> i32 {
if b ==0 { a } else { gcd(b, a % b) }
}
letmut g = nums_divide[0];
for&x in&nums_divide { g = gcd(g, x); }
letmut nums = nums;
nums.sort();
for (i, &x) in nums.iter().enumerate() {
if g % x ==0 { return i asi32; }
}
-1 }
}