[LeetCode] Minimum Split Into Subarrays With GCD Greater Than One

2436. Minimum Split Into Subarrays With GCD Greater Than One

You are given an array nums consisting of positive integers.

Split the array into one or more disjoint subarrays such that:

  • Each element of the array belongs to exactly one subarray, and
  • The GCD of the elements of each subarray is strictly greater than 1.

Return the minimum number of subarrays that can be obtained after the split.

Note that:

  • The GCD of a subarray is the largest positive integer that evenly divides all the elements of the subarray.
  • A subarray is a contiguous part of the array.
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int minimumSplits(vector<int>& A) {
int res = 1, g = A[0];
for(int i = 1; i < A.size(); i++) {
int gg = __gcd(g,A[i]);
if(gg == 1) g = A[i], res += 1;
else g = gg;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/01/PS/LeetCode/minimum-split-into-subarrays-with-gcd-greater-than-one/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.