Problem Description
Given an array of positive integers, find the length of the longest contiguous subarray that is "product equivalent". A subarray is product equivalent if the product of its elements is equal to the product of its greatest common divisor (GCD) and its least common multiple (LCM).
Key Insights
- For any two positive integers, it is a well-known identity that a * b = gcd(a, b) * lcm(a, b), so every subarray of length 2 will always be product equivalent.
- For subarrays of length 1, note that the identity only holds if the number is 1; because for any number x ≠ 1 the equality x != x*x.
- For subarrays of length ≥ 3, the equality may or may not hold. A brute-force enumeration is acceptable given that the maximum array length is only 100.
- The challenge is to correctly calculate the product, GCD, and LCM for each subarray. Although the product may grow large, the small input constraints (numbers ≤ 10) mean that even a brute-force calculation (using Python’s big integers, for example) is feasible.
- When computing LCM iteratively, remember that lcm(a, b) = a * b / gcd(a, b).
Space and Time Complexity
Time Complexity: O(n^2 * log(max(nums))) where n is the length of the array (subarray enumeration multiplied by cost of GCD/LCM operations) Space Complexity: O(1) extra space (ignoring the space needed for the output result)
Solution
The solution enumerates all possible contiguous subarrays. For each subarray, we compute:
- The product of all elements.
- The GCD of all elements.
- The LCM of all elements (by iteratively applying lcm on pairs). Then, we check if product == gcd * lcm for that subarray. If so, we update the maximum subarray length. Special care is taken with single-element subarrays, since the equality only holds when that single element is 1.
We use helper functions for GCD and LCM calculations. The algorithm is implemented in a brute-force manner as the constraints allow it, and the clarity outweighs the need for additional optimizations.