-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
40 lines (38 loc) · 962 Bytes
/
Solution.java
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
class Solution {
public int maxLength(int[] nums) {
int mx = 0, ml = 1;
for (int x : nums) {
mx = Math.max(mx, x);
ml = lcm(ml, x);
}
int maxP = ml * mx;
int n = nums.length;
int ans = 0;
for (int i = 0; i < n; ++i) {
int p = 1, g = 0, l = 1;
for (int j = i; j < n; ++j) {
p *= nums[j];
g = gcd(g, nums[j]);
l = lcm(l, nums[j]);
if (p == g * l) {
ans = Math.max(ans, j - i + 1);
}
if (p > maxP) {
break;
}
}
}
return ans;
}
private int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
private int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
}