Intuition
Grow a window from every start, keeping product, gcd and lcm as you add each element, and check the product == lcm * gcd rule in O(1) each step.
Explanation
Key idea
The rule to test is prod(arr) == lcm(arr) * gcd(arr). We cannot recompute the product, gcd and lcm from scratch for every subarray, but we can maintain all three incrementally: when we append one more number x to a window, the product multiplies by x, the gcd becomes gcd(old_gcd, x), and the lcm becomes old_lcm * x / gcd(old_lcm, x). So extending a window by one element costs only O(1).
Why we can stop early
Every value is between 1 and 10, so the lcm of any window can never exceed lcm(1..10) = 2520, and the gcd never exceeds 10. That means lcm * gcd is at most 2520 * 10 = 25200. The product, on the other hand, only grows as the window gets longer. Once the running product passes 25200 it can never again equal lcm * gcd, so we stop extending that window. This keeps the arithmetic small (no giant products) and makes the scan fast.
Walk-through on nums = [2, 3, 4, 5, 6]
Start a window at each index and extend it to the right:
- Start at index 1 (value 3): window [3] has prod 3, gcd 3, lcm 3 -> 3 != 9. Extend to [3, 4]: prod 12, gcd 1, lcm 12 -> 12 == 12 * 1, equivalent, length 2. Extend to [3, 4, 5]: prod 60, gcd 1, lcm 60 -> 60 == 60 * 1, equivalent, length 3! Extend to [3, 4, 5, 6]: prod 360, gcd 1, lcm 60 -> 360 != 60, not equivalent.
- No other start reaches length 3, so the answer is 3.
A window is product equivalent exactly when its non-1 values share no repeated prime factor across elements in a way that inflates the product beyond lcm * gcd; the incremental check captures this without any prime factorisation.
Complexity
- Time: O(n^2) in the worst case, but the early stop makes each window short in practice.
- Space: O(1) beyond the input.
Implementation
class Solution {
public int maxLength(int[] nums) {
int n = nums.length, best = 0;
for (int i = 0; i < n; i++) {
long prod = 1, g = 0, lcm = 1;
for (int j = i; j < n; j++) {
int x = nums[j];
prod *= x;
g = gcd(g, x);
lcm = lcm / gcd(lcm, x) * x;
// lcm <= 2520 and gcd <= 10 for values in [1, 10], so lcm * g
// never exceeds 25200; once the product passes that it can
// never match again, so stop extending this window.
if (prod > 25200) break;
if (prod == lcm * g) best = Math.max(best, j - i + 1);
}
}
return best;
}
private long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}