An array arr is called product equivalent if prod(arr) == lcm(arr) * gcd(arr), where:
prod(arr) is the product of all elements of arr.
gcd(arr) is the GCD of all elements of arr.
lcm(arr) is the LCM of all elements of arr.
Return the length of the longestproduct equivalentsubarray of nums.
Example 1:
Input:nums = [1,2,1,2,1,1,1]
Output:5
Explanation:
The longest product equivalent subarray is [1, 2, 1, 1, 1], where prod([1, 2, 1, 1, 1]) = 2, gcd([1, 2, 1, 1, 1]) = 1, and lcm([1, 2, 1, 1, 1]) = 2.
Example 2:
Input:nums = [2,3,4,5,6]
Output:3
Explanation:
The longest product equivalent subarray is [3, 4, 5].
Example 3:
Input:nums = [1,2,3,1,4,5,1]
Output:5
Constraints:
2 <= nums.length <= 100
1 <= nums[i] <= 10
Solutions
Solution 1
Thinking
The product equaling \(\gcd\cdot\operatorname{lcm}\) is an algebraic test on a subarray. With \(n\le 100\) and values \(\le 10\), we can enumerate every subarray while maintaining product, GCD, and LCM.
The product grows quickly. Once it exceeds \(\operatorname{lcm}(\textit{nums})\cdot\max(\textit{nums})\), a longer suffix cannot satisfy the identity, so the inner loop should stop.
We fix the left end \(i\), extend rightward updating \(p\), \(g\), and \(l\), record the length when \(p=g\cdot l\), and break when \(p\) is already too large.