LeetCode 题解工作台
最长乘积等价子数组
给你一个由 正整数 组成的数组 nums 。 如果一个数组 arr 满足 prod(arr) == lcm(arr) * gcd(arr) ,则称其为 乘积等价数组 ,其中: prod(arr) 表示 arr 中所有元素的乘积。 gcd(arr) 表示 arr 中所有元素的最大公因数 ( GCD )…
5
题型
4
代码语言
3
相关题
当前训练重点
简单 · 滑动窗口(状态滚动更新)
答案摘要
class Solution: def maxLength(self, nums: List[int]) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个由 正整数 组成的数组 nums。
如果一个数组 arr 满足 prod(arr) == lcm(arr) * gcd(arr),则称其为 乘积等价数组 ,其中:
prod(arr)表示arr中所有元素的乘积。gcd(arr)表示arr中所有元素的最大公因数 (GCD)。lcm(arr)表示arr中所有元素的最小公倍数 (LCM)。
返回数组 nums 的 最长 乘积等价 子数组 的长度。
示例 1:
输入: nums = [1,2,1,2,1,1,1]
输出: 5
解释:
最长的乘积等价子数组是 [1, 2, 1, 1, 1],其中 prod([1, 2, 1, 1, 1]) = 2, gcd([1, 2, 1, 1, 1]) = 1,以及 lcm([1, 2, 1, 1, 1]) = 2。
示例 2:
输入: nums = [2,3,4,5,6]
输出: 3
解释:
最长的乘积等价子数组是 [3, 4, 5]。
示例 3:
输入: nums = [1,2,3,1,4,5,1]
输出: 5
提示:
2 <= nums.length <= 1001 <= nums[i] <= 10
解题思路
方法一
class Solution:
def maxLength(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
max_p = lcm(*nums) * 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate can efficiently handle the updates for product, LCM, and GCD as the window slides.
- question_mark
Look for understanding of the sliding window technique and its application to this specific problem.
- question_mark
Assess the candidate's ability to handle edge cases effectively while maintaining performance.
常见陷阱
外企场景- error
Recalculating product, LCM, and GCD for every subarray instead of using a sliding window with running state.
- error
Failing to handle edge cases such as very small arrays or arrays without any valid subarrays.
- error
Not considering how to manage the state efficiently when the window expands or contracts.
进阶变体
外企场景- arrow_right_alt
Consider a variant where the numbers in the array are larger, requiring more efficient GCD and LCM calculations.
- arrow_right_alt
Change the problem to find the longest subarray where the product is exactly equal to a given constant.
- arrow_right_alt
Extend the problem to work with arrays containing negative numbers, adding complexity to the LCM and GCD calculations.