Input: nums =[2,6,3,4]Output: 4Explanation: We can do the following operations:- Choose index i =2 and replace nums[2]withgcd(3,4)=1. Now we have nums =[2,6,1,4].- Choose index i =1 and replace nums[1]withgcd(6,1)=1. Now we have nums =[2,1,1,4].- Choose index i =0 and replace nums[0]withgcd(2,1)=1. Now we have nums =[1,1,1,4].- Choose index i =2 and replace nums[3]withgcd(1,4)=1. Now we have nums =[1,1,1,1].
If the GCD of the whole array is not 1, it’s impossible. Otherwise, find the shortest subarray with GCD 1; we can propagate 1 to all elements in n-1 moves, but need extra moves to create the first 1.
#include<vector>#include<numeric>usingnamespace std;
classSolution {
public:int minOperations(vector<int>& nums) {
int n = nums.size(), minlen = n +1;
int allgcd = nums[0];
for (int x : nums) allgcd = gcd(allgcd, x);
if (allgcd !=1) return-1;
for (int i =0; i < n; ++i) {
int g = nums[i];
for (int j = i; j < n; ++j) {
g = gcd(g, nums[j]);
if (g ==1) {
minlen = min(minlen, j - i +1);
break;
}
}
}
return minlen -1+ n -1;
}
};
classSolution {
publicintminOperations(int[] nums) {
int n = nums.length, minlen = n + 1;
int allgcd = nums[0];
for (int x : nums) allgcd = gcd(allgcd, x);
if (allgcd != 1) return-1;
for (int i = 0; i < n; ++i) {
int g = nums[i];
for (int j = i; j < n; ++j) {
g = gcd(g, nums[j]);
if (g == 1) {
minlen = Math.min(minlen, j - i + 1);
break;
}
}
}
return minlen - 1 + n - 1;
}
privateintgcd(int a, int b) {
while (b != 0) {
int t = b; b = a % b; a = t;
}
return a;
}
}
classSolution {
funminOperations(nums: IntArray): Int {
fungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
val n = nums.size
var allgcd = nums[0]
for (x in nums) allgcd = gcd(allgcd, x)
if (allgcd !=1) return -1var minlen = n + 1for (i in0 until n) {
var g = nums[i]
for (j in i until n) {
g = gcd(g, nums[j])
if (g ==1) {
minlen = minOf(minlen, j - i + 1)
break }
}
}
return minlen - 1 + n - 1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from math import gcd
classSolution:
defminOperations(self, nums: list[int]) -> int:
from math import gcd
n = len(nums)
allgcd = nums[0]
for x in nums:
allgcd = gcd(allgcd, x)
if allgcd !=1:
return-1 minlen = n +1for i in range(n):
g = nums[i]
for j in range(i, n):
g = gcd(g, nums[j])
if g ==1:
minlen = min(minlen, j - i +1)
breakreturn minlen -1+ n -1
impl Solution {
pubfnmin_operations(nums: Vec<i32>) -> i32 {
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 {
let t = b; b = a % b; a = t;
}
a
}
let n = nums.len() asi32;
letmut allgcd = nums[0];
for&x in&nums { allgcd = gcd(allgcd, x); }
if allgcd !=1 { return-1; }
letmut minlen = n +1;
for i in0..n {
letmut g = nums[i asusize];
for j in i..n {
g = gcd(g, nums[j asusize]);
if g ==1 {
minlen = minlen.min(j - i +1);
break;
}
}
}
minlen -1+ n -1 }
}