Skip to content

Commit 816e349

Browse files
committed
Maximum Product Subarray
1 parent e80c4d4 commit 816e349

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

152-maximum-product-subarray.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/maximum-product-subarray/
3+
4+
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has
5+
the largest product.
6+
7+
Example 1:
8+
Input: [2,3,-2,4]
9+
Output: 6
10+
Explanation: [2,3] has the largest product 6.
11+
12+
Example 2:
13+
Input: [-2,0,-1]
14+
Output: 0
15+
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
16+
"""
17+
class Solution(object):
18+
def maxProduct(self, nums):
19+
"""
20+
:type nums: List[int]
21+
:rtype: int
22+
"""
23+
maxp = minp = res = nums[0]
24+
for i in range(1,len(nums)):
25+
if nums[i] < 0:
26+
maxp, minp = minp, maxp
27+
maxp = max(nums[i], nums[i]*maxp)
28+
minp = min(nums[i], nums[i]*minp)
29+
res = max(res, maxp)
30+
return res

0 commit comments

Comments
 (0)