Skip to content

Commit 2b7af01

Browse files
authored
Create 152_Maximum_Product_Subarray.md
1 parent e0de0be commit 2b7af01

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

152_Maximum_Product_Subarray.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## 152. Maximum Product Subarray
2+
3+
4+
```
5+
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
6+
7+
It is guaranteed that the answer will fit in a 32-bit integer.
8+
9+
A subarray is a contiguous subsequence of the array.
10+
11+
12+
13+
Example 1:
14+
15+
Input: nums = [2,3,-2,4]
16+
Output: 6
17+
Explanation: [2,3] has the largest product 6.
18+
Example 2:
19+
20+
Input: nums = [-2,0,-1]
21+
Output: 0
22+
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
23+
24+
25+
Constraints:
26+
27+
1 <= nums.length <= 2 * 104
28+
-10 <= nums[i] <= 10
29+
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
30+
31+
```
32+
33+
34+
```python
35+
class Solution:
36+
def maxProduct(self, nums: List[int]) -> int:
37+
# Kadane's Algorithm
38+
max_cur = nums[0]
39+
max_global = nums[0]
40+
min_cur = nums[0]
41+
42+
for i in range(1, len(nums)):
43+
prev_max_cur = max_cur
44+
max_cur = max(nums[i], max(max_cur * nums[i], min_cur * nums[i]))
45+
min_cur = min(nums[i], min(prev_max_cur * nums[i], min_cur*nums[i]))
46+
max_global = max(max_global, max_cur)
47+
48+
49+
return max_global
50+
```
51+
52+
53+
```
54+
Runtime: 44 ms, faster than 98.65% of Python3 online submissions for Maximum Product Subarray.
55+
Memory Usage: 14.3 MB, less than 83.87% of Python3 online submissions for Maximum Product Subarray.
56+
```

0 commit comments

Comments
 (0)