File tree 2 files changed +64
-0
lines changed
2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 思路一 O(n2)
2
+ // Runtime: 352 ms, faster than 7.74% of C++ online submissions for Maximum Product Subarray.
3
+ // Memory Usage: 8.9 MB, less than 92.86% of C++ online submissions for Maximum Product Subarray.
4
+ class Solution {
5
+ public:
6
+ int maxProduct (vector<int >& nums)
7
+ {
8
+ int res = INT_MIN;
9
+ for (int i = 0 ; i < nums.size (); i++)
10
+ {
11
+ if (nums[i] == 0 )
12
+ {
13
+ res = max (res, 0 );
14
+ continue ;
15
+ }
16
+
17
+ int curseq = 1 ;
18
+ for (int j = i; j < nums.size (); j++)
19
+ {
20
+ curseq *= nums[j];
21
+ res = max (res, curseq);
22
+ }
23
+ }
24
+ return res;
25
+ }
26
+ };
27
+
28
+ // 思路二
29
+ // https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity
30
+ // Runtime: 8 ms, faster than 100.00% of C++ online submissions for Maximum Product Subarray.
31
+ // Memory Usage: 8.9 MB, less than 98.66% of C++ online submissions for Maximum Product Subarray.
32
+ class Solution
33
+ {
34
+ public:
35
+ int maxProduct (vector<int >& nums)
36
+ {
37
+ int maxpod = nums[0 ], imax = nums[0 ], imin = nums[0 ];
38
+ for (int i = 1 ; i < nums.size (); i++)
39
+ {
40
+ if (nums[i] < 0 )
41
+ swap (imin, imax);
42
+
43
+ imax = max (nums[i], imax * nums[i]);
44
+ imin = min (nums[i], imin * nums[i]);
45
+
46
+ maxpod = max (maxpod, imax);
47
+ }
48
+ return maxpod;
49
+ }
50
+ };
Original file line number Diff line number Diff line change
1
+ # Runtime: 44 ms, faster than 95.81% of Python3 online submissions for Maximum Product Subarray.
2
+ # Memory Usage: 12.7 MB, less than 46.41% of Python3 online submissions for Maximum Product Subarray.
3
+ class Solution :
4
+ def maxProduct (self , nums : 'List[int]' ) -> 'int' :
5
+ maxpod = imin = imax = nums [0 ]
6
+
7
+ for i in range (1 , len (nums )):
8
+ if nums [i ] < 0 :
9
+ imin , imax = imax , imin
10
+ imax = max (nums [i ], imax * nums [i ])
11
+ imin = min (nums [i ], imin * nums [i ])
12
+
13
+ maxpod = max (maxpod , imax )
14
+ return maxpod
You can’t perform that action at this time.
0 commit comments