Maximum Subarray With Equal Products Problem
Description
LeetCode Problem 3411.
You are given an array of positive integers nums.
An array arr is called product equivalent if prod(arr) == lcm(arr) * gcd(arr), where:
prod(arr)is the product of all elements ofarr.gcd(arr)is the GCD of all elements ofarr.lcm(arr)is the LCM of all elements ofarr.
Return the length of the longest product equivalent subarray 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 <= 1001 <= nums[i] <= 10
Solution
Approach: Enumeration with Pruning
For a subarray, the condition is product == gcd * lcm. The array is short (n <= 100), so try every start i and extend the end j, updating the product, the gcd and the lcm as we go. Record j - i + 1 whenever the condition holds.
The product grows much faster than gcd * lcm. If it ever exceeds lcm(nums) * max(nums), the condition cannot hold for any longer subarray from this start, so we stop extending.
Complexity: O(n^2 log U) time in the worst case, where U is the largest value; the pruning makes it far smaller in practice. O(1) extra space.
from math import gcd
def lcm(a, b):
return a // gcd(a, b) * b
class Solution:
def maxLength(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
ml = 1
for x in nums:
ml = lcm(ml, x)
max_p = ml * max(nums)
for i in range(n):
p, g, l = 1, 0, 1
for j in range(i, n):
p *= nums[j]
g = gcd(g, nums[j])
l = lcm(l, nums[j])
if p == g * l:
ans = max(ans, j - i + 1)
if p > max_p:
break
return ans