Input: nums =[12,6,3,14,8]Output: 2Explanation: We can split the array into the subarrays:[12,6,3] and [14,8].- The GCD of 12,6 and 3is3, which is strictly greater than 1.- The GCD of 14 and 8is2, which is strictly greater than 1.It can be shown that splitting the array into one subarray will make the GCD =1.
Example 2:
1
2
3
Input: nums =[4,12,6,14]Output: 1Explanation: We can split the array into only one subarray, which is the whole array.
We want to split the array into the minimum number of contiguous subarrays such that the GCD of each subarray is strictly greater than 1. We can greedily extend each subarray as far as possible, starting a new subarray only when the GCD drops to 1.
Iterate through the array, maintaining the current GCD. If adding the next element causes the GCD to become 1, start a new subarray. Count the number of subarrays.
#include<numeric>classSolution {
public:int minimumSplits(vector<int>& nums) {
int ans =1, cur = nums[0];
for (int i =1; i < nums.size(); ++i) {
cur = gcd(cur, nums[i]);
if (cur ==1) {
ans++;
cur = nums[i];
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcgcd(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna}
funcminimumSplits(nums []int) int {
ans, cur:=1, nums[0]
fori:=1; i < len(nums); i++ {
cur = gcd(cur, nums[i])
ifcur==1 {
ans++cur = nums[i]
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
privateintgcd(int a, int b) {
while (b != 0) {
int t = b; b = a % b; a = t;
}
return a;
}
publicintminimumSplits(int[] nums) {
int ans = 1, cur = nums[0];
for (int i = 1; i < nums.length; i++) {
cur = gcd(cur, nums[i]);
if (cur == 1) {
ans++;
cur = nums[i];
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
privatefungcd(a: Int, b: Int): Int {
var x = a; var y = b
while (y !=0) { val t = y; y = x % y; x = t }
return x
}
funminimumSplits(nums: IntArray): Int {
var ans = 1; var cur = nums[0]
for (i in1 until nums.size) {
cur = gcd(cur, nums[i])
if (cur ==1) {
ans++ cur = nums[i]
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
from math import gcd
classSolution:
defminimumSplits(self, nums: list[int]) -> int:
ans, cur =1, nums[0]
for num in nums[1:]:
cur = gcd(cur, num)
if cur ==1:
ans +=1 cur = num
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnminimum_splits(nums: Vec<i32>) -> i32 {
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 { let t = b; b = a % b; a = t; } a
}
letmut ans =1;
letmut cur = nums[0];
for&num in&nums[1..] {
cur = gcd(cur, num);
if cur ==1 {
ans +=1;
cur = num;
}
}
ans
}
}