Skip to content

2344. Minimum Deletions to Make Array Divisible 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int minOperations(vector<int>& nums, vector<int>& numsDivide) {
    const int gcd = getGCD(numsDivide);

    ranges::sort(nums);

    for (int i = 0; i < nums.size(); ++i)
      if (gcd % nums[i] == 0)
        return i;

    return -1;
  }

 private:
  int getGCD(const vector<int>& nums) {
    int gcd = nums[0];
    for (const int num : nums)
      gcd = __gcd(gcd, num);
    return gcd;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int minOperations(int[] nums, int[] numsDivide) {
    final int gcd = getGCD(numsDivide);

    Arrays.sort(nums);

    for (int i = 0; i < nums.length; ++i)
      if (gcd % nums[i] == 0)
        return i;

    return -1;
  }

  private int getGCD(int[] nums) {
    int g = nums[0];
    for (final int num : nums)
      g = gcd(g, num);
    return g;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def minOperations(self, nums: list[int], numsDivide: list[int]) -> int:
    gcd = functools.reduce(math.gcd, numsDivide)

    for i, num in enumerate(sorted(nums)):
      if gcd % num == 0:
        return i

    return -1