3411. Maximum Subarray With Equal Products
EasyView on LeetCode
Time: O(n^2 log A)
Space: O(1)
Problem Overview
A subarray is product equivalent when its product equals its LCM times its GCD.
Intuition
A subarray is product equivalent when its product equals its LCM times its GCD. With length at most 100 and values at most 10, every subarray can be checked while rolling those three quantities. The right hand side is at most lcm of 1 through 10 times 10, so once the running product grows past that bound the identity can never hold and the inner scan can stop.
Algorithm
- 1For each left endpoint i, start product at 1, LCM at 1, and GCD at 0.
- 2Extend the right endpoint j, multiplying nums[j] into the product and folding it into the LCM and GCD.
- 3Break early when the product exceeds 2520 times 10.
- 4Whenever product equals LCM times GCD, update the answer with the window length.
- 5Return the longest length seen.
Example Walkthrough
Input: nums = [1, 2, 1, 2, 1, 1, 1]
- 1.Short windows that mix 1 and 2 satisfy the identity because the product stays small.
- 2.The window [1, 2, 1, 1, 1] has product 2, LCM 2, and GCD 1, so it qualifies with length 5.
- 3.No longer product equivalent window exists, so the answer is 5.
Output: 5
Common Pitfalls
- •Use a 64 bit product. Even with early breaks, an int multiply can overflow before the bound check.
- •Compute LCM as a / gcd(a, b) * b to reduce intermediate overflow risk.
- •A single element x works only when x equals x times x, so only 1 is product equivalent alone.
- •Do not forget that GCD starts at 0 so the first fold becomes the first element.
3411.cs
C#
// Approach: With n at most 100 and values at most 10, check every subarray
// while rolling product, LCM, and GCD. The identity prod == lcm * gcd can
// hold only while the product stays at most lcm(1..10) * 10, so stop the
// inner scan once the product exceeds that bound.
// Time: O(n^2 log A) Space: O(1)
public class Solution
{
public int MaxLength(int[] nums)
{
const int MaxProd = 2520 * 10; // lcm(1..10) * max(nums[i])
int n = nums.Length;
int ans = 0;
for (int i = 0; i < n; ++i)
{
long prod = 1;
int l = 1;
int g = 0;
for (int j = i; j < n; ++j)
{
prod *= nums[j];
if (prod > MaxProd)
break;
l = Lcm(l, nums[j]);
g = Gcd(g, nums[j]);
if (prod == (long)l * g)
ans = Math.Max(ans, j - i + 1);
}
}
return ans;
}
private static int Gcd(int a, int b)
{
while (b != 0)
{
int t = a % b;
a = b;
b = t;
}
return a;
}
private static int Lcm(int a, int b)
{
return a / Gcd(a, b) * b;
}
}
Was this solution helpful?