@@ -4,28 +4,25 @@ https://leetcode.com/problems/maximum-product-subarray/description/
4
4
5
5
## 题目描述
6
6
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 ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
9
8
10
- Example 1:
9
+
11
10
12
- Input: [2,3,-2,4]
13
- Output: 6
14
- Explanation: [2,3] has the largest product 6.
15
- Example 2:
11
+ 示例 1:
16
12
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:
20
17
21
- ```
18
+ 输入: [ -2,0,-1]
19
+ 输出: 0
20
+ 解释: 结果不能为 2, 因为 [ -2,-1] 不是子数组。
22
21
23
- ## 思路
24
22
25
- > 这道题目的通过率非常低
23
+ ## 思路
26
24
27
- 这道题目要我们求解连续的 n 个数中乘积最大的积是多少。这里提到了连续,笔者首先
28
- 想到的就是滑动窗口,但是这里比较特殊,我们不能仅仅维护一个最大值,因此最小值(比如-20)乘以一个比较小的数(比如-10)
25
+ 这道题目要我们求解连续的 n 个数中乘积最大的积是多少。这里提到了连续,笔者首先想到的就是滑动窗口,但是这里比较特殊,我们不能仅仅维护一个最大值,因此最小值(比如-20)乘以一个比较小的数(比如-10)
29
26
可能就会很大。 因此这种思路并不方便。
30
27
31
28
首先来暴力求解,我们使用两层循环来枚举所有可能项,这种解法的时间复杂度是O(n^2), 代码如下:
@@ -36,7 +33,6 @@ var maxProduct = function(nums) {
36
33
let temp = null ;
37
34
for (let i = 0 ; i < nums .length ; i++ ) {
38
35
temp = nums[i];
39
- max = Math .max (temp, max);
40
36
for (let j = i + 1 ; j < nums .length ; j++ ) {
41
37
temp *= nums[j];
42
38
max = Math .max (temp, max);
@@ -47,9 +43,11 @@ var maxProduct = function(nums) {
47
43
};
48
44
```
49
45
50
- 因此我们需要同时记录乘积最大值和乘积最小值,然后比较元素和这两个的乘积,去不断更新最大值。
51
46
52
- ![ ] ( https://tva1.sinaimg.cn/large/0082zybply1gcatuvun39j30gr08kt9l.jpg )
47
+
48
+ 前面说了` 最小值(比如-20)乘以一个比较小的数(比如-10)可能就会很大 ` 。因此我们需要同时记录乘积最大值和乘积最小值,然后比较元素和这两个的乘积,去不断更新最大值。当然,我们也可以选择只取当前元素。因此实际上我们的选择有三种,而如何选择就取决于哪个选择带来的价值最大(乘积最大或者最小)。
49
+
50
+ ![ ] ( https://pic.leetcode-cn.com/7d39989d10d982d44cbd6b6f693cf5171865c0654f7c3754e27ec1afc2c0de5d.jpg )
53
51
54
52
这种思路的解法由于只需要遍历一次,其时间复杂度是O(n),代码见下方代码区。
55
53
@@ -137,3 +135,7 @@ var maxProduct = function(nums) {
137
135
** 复杂度分析**
138
136
- 时间复杂度:$O(N)$
139
137
- 空间复杂度:$O(1)$
138
+
139
+ 更多题解可以访问我的LeetCode题解仓库:https://github.com/azl397985856/leetcode 。 目前已经30K star啦。
140
+
141
+ 大家也可以关注我的公众号《脑洞前端》获取更多更新鲜的LeetCode题解
0 commit comments