#3411
Maximum Subarray With Equal Products
EasyArrayMathSliding WindowEnumerationNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of checking all subarrays, we can use a sliding window approach to dynamically calculate the product, GCD, and LCM while maintaining a valid subarray. This reduces the number of calculations significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers for the sliding window and variables for product, GCD, and LCM.
- 2Step 2: Expand the window by moving the right pointer and update product, GCD, and LCM.
- 3Step 3: If the product is not equal to GCD * LCM, move the left pointer to shrink the window until the condition is satisfied or the window is empty.
- 4Step 4: Keep track of the maximum length of valid subarrays found.
solution.py31 lines
1# Full working Python code
2import math
3from functools import reduce
4
5def gcd(a, b):
6 while b:
7 a, b = b, a % b
8 return a
9
10def lcm(a, b):
11 return abs(a * b) // gcd(a, b)
12
13def maxProductEquivalentSubarray(nums):
14 n = len(nums)
15 max_length = 0
16 left = 0
17 product = 1
18 current_gcd = 0
19 current_lcm = 1
20 for right in range(n):
21 product *= nums[right]
22 current_gcd = gcd(current_gcd, nums[right]) if current_gcd else nums[right]
23 current_lcm = lcm(current_lcm, nums[right])
24 while product != current_gcd * current_lcm and left <= right:
25 product //= nums[left]
26 left += 1
27 current_gcd = reduce(gcd, nums[left:right + 1])
28 current_lcm = reduce(lcm, nums[left:right + 1])
29 max_length = max(max_length, right - left + 1)
30 return max_length
31ℹ
Complexity note: This complexity is achieved because we only traverse the array once using the sliding window technique.
- 1The relationship between product, GCD, and LCM is crucial for determining valid subarrays.
- 2Using a sliding window can significantly reduce the number of calculations needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.