Maximum Subarray With Equal Products - Problem

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 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 longest product equivalent subarray of nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 1
💡 Note: Only single-element subarrays are product equivalent. For [1]: product=1, gcd=1, lcm=1, so 1 = 1×1 ✓. For [1,2]: product=2, gcd=1, lcm=2, so 2 ≠ 1×2 ✗.
Example 2 — Multiple Equal Elements
$ Input: nums = [6,6]
Output: 2
💡 Note: The subarray [6,6] is product equivalent: product=36, gcd=6, lcm=6, so 36 = 6×6 ✓. Length is 2.
Example 3 — Single Element Only
$ Input: nums = [2,4,8]
Output: 2
💡 Note: Single elements don't work since for [a]: product=a, gcd=a, lcm=a requires a=a×a (impossible for a>1). But [2,4] has product=8, gcd=2, lcm=4, so 8 = 2×4 ✓, giving length 2.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Maximum Subarray With Equal Products INPUT nums = [1, 2, 3, 4] 1 idx 0 2 idx 1 3 idx 2 4 idx 3 Product Equivalent Condition: prod(arr) == lcm(arr) * gcd(arr) prod = product of all elements lcm = least common multiple Check subarray [1,2]: prod=2, lcm=2, gcd=1 2 == 2*1? YES Check subarray [2,3]: prod=6, lcm=6, gcd=1 6 == 6*1? YES but... ALGORITHM STEPS 1 Math Insight prod = lcm * gcd holds when elements are pairwise coprime 2 Early Termination Stop extending when condition fails 3 Iterate Subarrays Check each starting point Extend while valid 4 Track Maximum Update max length for valid subarrays Checking Subarrays: [1]: prod=1, lcm*gcd=1 OK [2]: prod=2, lcm*gcd=2 OK [1,2]: prod=2, lcm*gcd=2 OK [2,4]: prod=8, lcm*gcd=8 FAIL FINAL RESULT Longest valid subarray length: 1 Analysis Results: Single elements always valid No longer valid subarray found [1,2] fails extended check [2,4] shares factor 2 Valid Length-1 Subarrays: [1] [2] [3] [4] All single elements: OK Key Insight: Early Mathematical Pruning The equation prod(arr) = lcm(arr) * gcd(arr) holds only when elements share specific coprimality properties. Once the condition fails for a subarray, extending it will also fail. This allows early termination, significantly reducing time complexity compared to checking all O(n^2) subarrays naively. TutorialsPoint - Maximum Subarray With Equal Products | Optimized - Early Mathematical Insights
Asked in
Google 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen