-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-75.java
More file actions
41 lines (39 loc) · 941 Bytes
/
leet-code-q-75.java
File metadata and controls
41 lines (39 loc) · 941 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public int minOperations(int[] nums) {
int n = nums.length;
int num1 = 0;
int g = 0;
for (int x : nums) {
if (x == 1) {
num1++;
}
g = gcd(g, x);
}
if (num1 > 0) {
return n - num1;
}
if (g > 1) {
return -1;
}
int minLen = n;
for (int i = 0; i < n; i++) {
int currentGcd = 0;
for (int j = i; j < n; j++) {
currentGcd = gcd(currentGcd, nums[j]);
if (currentGcd == 1) {
minLen = Math.min(minLen, j - i + 1);
break;
}
}
}
return minLen + n - 2;
}
private int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}