Skip to content

2436. Minimum Split Into Subarrays With GCD Greater Than One

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int minimumSplits(vector<int>& nums) {
    int ans = 1;
    int gcd = nums[0];

    for (const int num : nums) {
      const int newGcd = __gcd(gcd, num);
      if (newGcd > 1) {
        gcd = newGcd;
      } else {
        gcd = num;
        ++ans;
      }
    }

    return ans;
  }
};
 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 minimumSplits(int[] nums) {
    int ans = 1;
    int gcd = nums[0];

    for (final int num : nums) {
      final int newGcd = gcd(gcd, num);
      if (newGcd > 1) {
        gcd = newGcd;
      } else {
        gcd = num;
        ++ans;
      }
    }

    return ans;
  }

  private int gcd(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
class Solution:
  def minimumSplits(self, nums: list[int]) -> int:
    ans = 1
    gcd = nums[0]

    for num in nums:
      newGcd = math.gcd(gcd, num)
      if newGcd > 1:
        gcd = newGcd
      else:
        gcd = num
        ans += 1

    return ans