-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path152.py
More file actions
49 lines (37 loc) · 1.05 KB
/
152.py
File metadata and controls
49 lines (37 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'''
152. Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number)
which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
Subscribe to see which companies asked this question
'''
import sys
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# runtime 52ms
if len(nums) == 1:
return nums[0]
maxPro = - sys.maxsize - 1
minPro = sys.maxsize
ret = [maxPro, minPro]
for num in nums:
if num < 0:
maxPro, minPro = minPro, maxPro
maxPro = max(num, maxPro * num)
minPro = min(num, minPro * num)
ret[0] = max(ret[0], maxPro)
ret[1] = min(ret[1], minPro)
# print(ret)
return ret[0]
def test():
num = [-2,0,-1]
nums = [2,3,-2,-4]
sol = Solution()
print(sol.maxProduct(nums))
if __name__ == "__main__":
test()