LeetCode 题解工作台

最长乘积等价子数组

给你一个由 正整数 组成的数组 nums 。 如果一个数组 arr 满足 prod(arr) == lcm(arr) * gcd(arr) ,则称其为 乘积等价数组 ,其中: prod(arr) 表示 arr 中所有元素的乘积。 gcd(arr) 表示 arr 中所有元素的最大公因数 ( GCD )…

category

5

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 滑动窗口(状态滚动更新)

bolt

答案摘要

class Solution: def maxLength(self, nums: List[int]) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由 正整数 组成的数组 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 <= 100
  • 1 <= nums[i] <= 10
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

最长乘积等价子数组题解:滑动窗口(状态滚动更新) | LeetCode #3411 简单