Skip to content

Commit d9fb730

Browse files
authored
Update 152.maximum-product-subarray.md
1 parent 95aa868 commit d9fb730

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

problems/152.maximum-product-subarray.md

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,25 @@ https://leetcode.com/problems/maximum-product-subarray/description/
44

55
## 题目描述
66

7-
```
8-
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
7+
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
98

10-
Example 1:
9+
 
1110

12-
Input: [2,3,-2,4]
13-
Output: 6
14-
Explanation: [2,3] has the largest product 6.
15-
Example 2:
11+
示例 1:
1612

17-
Input: [-2,0,-1]
18-
Output: 0
19-
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
13+
输入: [2,3,-2,4]
14+
输出: 6
15+
解释: 子数组 [2,3] 有最大乘积 6。
16+
示例 2:
2017

21-
```
18+
输入: [-2,0,-1]
19+
输出: 0
20+
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
2221

23-
## 思路
2422

25-
> 这道题目的通过率非常低
23+
## 思路
2624

27-
这道题目要我们求解连续的 n 个数中乘积最大的积是多少。这里提到了连续,笔者首先
28-
想到的就是滑动窗口,但是这里比较特殊,我们不能仅仅维护一个最大值,因此最小值(比如-20)乘以一个比较小的数(比如-10)
25+
这道题目要我们求解连续的 n 个数中乘积最大的积是多少。这里提到了连续,笔者首先想到的就是滑动窗口,但是这里比较特殊,我们不能仅仅维护一个最大值,因此最小值(比如-20)乘以一个比较小的数(比如-10)
2926
可能就会很大。 因此这种思路并不方便。
3027

3128
首先来暴力求解,我们使用两层循环来枚举所有可能项,这种解法的时间复杂度是O(n^2), 代码如下:
@@ -36,7 +33,6 @@ var maxProduct = function(nums) {
3633
let temp = null;
3734
for (let i = 0; i < nums.length; i++) {
3835
temp = nums[i];
39-
max = Math.max(temp, max);
4036
for (let j = i + 1; j < nums.length; j++) {
4137
temp *= nums[j];
4238
max = Math.max(temp, max);
@@ -47,9 +43,11 @@ var maxProduct = function(nums) {
4743
};
4844
```
4945

50-
因此我们需要同时记录乘积最大值和乘积最小值,然后比较元素和这两个的乘积,去不断更新最大值。
5146

52-
![](https://tva1.sinaimg.cn/large/0082zybply1gcatuvun39j30gr08kt9l.jpg)
47+
48+
前面说了`最小值(比如-20)乘以一个比较小的数(比如-10)可能就会很大` 。因此我们需要同时记录乘积最大值和乘积最小值,然后比较元素和这两个的乘积,去不断更新最大值。当然,我们也可以选择只取当前元素。因此实际上我们的选择有三种,而如何选择就取决于哪个选择带来的价值最大(乘积最大或者最小)。
49+
50+
![](https://pic.leetcode-cn.com/7d39989d10d982d44cbd6b6f693cf5171865c0654f7c3754e27ec1afc2c0de5d.jpg)
5351

5452
这种思路的解法由于只需要遍历一次,其时间复杂度是O(n),代码见下方代码区。
5553

@@ -137,3 +135,7 @@ var maxProduct = function(nums) {
137135
**复杂度分析**
138136
- 时间复杂度:$O(N)$
139137
- 空间复杂度:$O(1)$
138+
139+
更多题解可以访问我的LeetCode题解仓库:https://github.com/azl397985856/leetcode 。 目前已经30K star啦。
140+
141+
大家也可以关注我的公众号《脑洞前端》获取更多更新鲜的LeetCode题解

0 commit comments

Comments
 (0)