Skip to content

Commit 9286af4

Browse files
committed
Maximum Product Subarray
1 parent 37e0cd4 commit 9286af4

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

152 Maximum Product Subarray.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'''
2+
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
3+
4+
For example, given the array [2,3,-2,4],
5+
the contiguous subarray [2,3] has the largest product = 6.
6+
'''
7+
8+
class Solution(object):
9+
def maxProduct(self, nums):
10+
"""
11+
:type nums: List[int]
12+
:rtype: int
13+
"""
14+
positive, negative = nums[0], nums[0]
15+
result = nums[0]
16+
for num in nums[1:]:
17+
positive, negative = max(num, positive * num, negative * num), min(num,
18+
positive * num, negative * num)
19+
result = max(result, positive)
20+
return result
21+
22+
23+
if __name__ == "__main__":
24+
assert Solution().maxProduct([2, 3, -2, 4]) == 6

0 commit comments

Comments
 (0)