LeetCode 题解工作台
乘积最大子数组
给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续 子数组 (该子数组中至少包含一个数字),并返回该子数组所对应的乘积。 测试用例的答案是一个 32-位 整数。 请注意 ,一个只包含一个元素的数组的乘积是这个元素的值。 示例 1: 输入: nums = [2,3,-2,4] 输出: 6 …
2
题型
8
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义两个变量 和 ,其中 表示以 结尾的乘积最大子数组的乘积,而 表示以 结尾的乘积最小子数组的乘积。初始时 和 都等于 。答案为所有 中的最大值。 从 开始,我们可以考虑将第 个数 添加到前面的乘积最大或者乘积最小的子数组乘积的后面,或者单独作为一个子数组乘积(即此时子数组长度只有 )。我们将此前的乘积最大值记为 ,乘积最小值记为 ,那么 $f = \max(f, ff…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续 子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
请注意,一个只包含一个元素的数组的乘积是这个元素的值。
示例 1:
输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: nums = [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
提示:
1 <= nums.length <= 2 * 104-10 <= nums[i] <= 10nums的任何子数组的乘积都 保证 是一个 32-位 整数
解题思路
方法一:动态规划
我们定义两个变量 和 ,其中 表示以 结尾的乘积最大子数组的乘积,而 表示以 结尾的乘积最小子数组的乘积。初始时 和 都等于 。答案为所有 中的最大值。
从 开始,我们可以考虑将第 个数 添加到前面的乘积最大或者乘积最小的子数组乘积的后面,或者单独作为一个子数组乘积(即此时子数组长度只有 )。我们将此前的乘积最大值记为 ,乘积最小值记为 ,那么 ,而 。接下来,我们更新答案 ,然后继续计算下一个位置。
最后的答案即为 。
时间复杂度 ,其中 是数组 的长度。我们只需要遍历数组一次即可求得答案。空间复杂度 。
class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = f = g = nums[0]
for x in nums[1:]:
ff, gg = f, g
f = max(x, ff * x, gg * x)
g = min(x, ff * x, gg * x)
ans = max(ans, f)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate explain how negative numbers affect the product and how this is handled in the solution?
- question_mark
Does the candidate demonstrate an understanding of dynamic programming techniques, specifically state transition?
- question_mark
How efficiently can the candidate discuss and apply space optimization in dynamic programming problems?
常见陷阱
外企场景- error
Forgetting to handle negative numbers correctly and assuming that the largest product will always be from the largest values.
- error
Not considering zero as a product, which could reset the subarray product.
- error
Using excessive space by storing all subarray products instead of just tracking the current max and min products.
进阶变体
外企场景- arrow_right_alt
Modify the problem to consider circular subarrays where the subarray can wrap around the array.
- arrow_right_alt
Extend the problem to handle larger integer ranges, potentially using BigInteger or similar data types.
- arrow_right_alt
Introduce a constraint where the array has multiple zeroes, and check if the algorithm handles this efficiently.