File tree Expand file tree Collapse file tree 1 file changed +27
-17
lines changed Expand file tree Collapse file tree 1 file changed +27
-17
lines changed Original file line number Diff line number Diff line change @@ -56,7 +56,6 @@ var maxProduct = function(nums) {
56
56
## 关键点
57
57
58
58
- 同时记录乘积最大值和乘积最小值
59
-
60
59
## 代码
61
60
62
61
代码支持:Python3,JavaScript
@@ -86,27 +85,15 @@ class Solution:
86
85
```
87
86
88
87
89
- JavaScript Code:
88
+ ** 复杂度分析**
89
+ - 时间复杂度:$O(N)$
90
+ - 空间复杂度:$O(N)$
90
91
91
- ``` js
92
- var maxProduct = function (nums ) {
93
- let max = nums[0 ];
94
- let min = nums[0 ];
95
- let res = nums[0 ];
96
92
97
- for (let i = 1 ; i < nums .length ; i++ ) {
98
- let tmp = min;
99
- min = Math .min (nums[i], Math .min (max * nums[i], min * nums[i])); // 取最小
100
- max = Math .max (nums[i], Math .max (max * nums[i], tmp * nums[i])); // / 取最大
101
- res = Math .max (res, max);
102
- }
103
- return res;
104
- };
105
- ```
106
93
当我们知道动态转移方程的时候,其实应该发现了。我们的dp[ i] 只和 dp[ i - 1] 有关,这是一个空间优化的信号,告诉我们` 可以借助两个额外变量记录即可 ` 。
107
94
108
95
109
- 代码( Python3):
96
+ Python3 Code:
110
97
111
98
112
99
``` python
@@ -127,3 +114,26 @@ class Solution:
127
114
return ans
128
115
129
116
```
117
+
118
+ JavaScript Code:
119
+
120
+ ``` js
121
+ var maxProduct = function (nums ) {
122
+ let max = nums[0 ];
123
+ let min = nums[0 ];
124
+ let res = nums[0 ];
125
+
126
+ for (let i = 1 ; i < nums .length ; i++ ) {
127
+ let tmp = min;
128
+ min = Math .min (nums[i], Math .min (max * nums[i], min * nums[i])); // 取最小
129
+ max = Math .max (nums[i], Math .max (max * nums[i], tmp * nums[i])); // / 取最大
130
+ res = Math .max (res, max);
131
+ }
132
+ return res;
133
+ };
134
+ ```
135
+
136
+
137
+ ** 复杂度分析**
138
+ - 时间复杂度:$O(N)$
139
+ - 空间复杂度:$O(1)$
You can’t perform that action at this time.
0 commit comments