Skip to content

Commit 989fadc

Browse files
committed
- Maximum Product Subarray #270
1 parent 22e8dd8 commit 989fadc

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

maximum-product-subarray/ayosecu.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(nums)
6+
- Space Complexity: O(1)
7+
"""
8+
def maxProduct(self, nums: List[int]) -> int:
9+
max_now, max_prod, min_prod = nums[0], nums[0], nums[0]
10+
11+
for num in nums[1:]:
12+
if num < 0:
13+
# if number is negative, swap the min/max value
14+
max_prod, min_prod = min_prod, max_prod
15+
16+
max_prod = max(num, max_prod * num)
17+
min_prod = min(num, min_prod * num)
18+
max_now = max(max_now, max_prod)
19+
20+
return max_now
21+
22+
tc = [
23+
([2,3,-2,4], 6),
24+
([-2,0,-1], 0)
25+
]
26+
27+
sol = Solution()
28+
for i, (n, e) in enumerate(tc, 1):
29+
r = sol.maxProduct(n)
30+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)