Skip to content

Commit a42e777

Browse files
committed
solve: maximum product subarray
1 parent 2d8ab89 commit a42e777

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

maximum-product-subarray/evan.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def maxProduct(self, nums: List[int]) -> int:
6+
if not nums:
7+
return 0
8+
9+
local_max_product = nums[0]
10+
min_product = nums[0]
11+
global_max_product = nums[0]
12+
13+
for i in range(1, len(nums)):
14+
current = nums[i]
15+
16+
temp_max = max(
17+
# the current element alone could be the new maximum product subarray.
18+
current,
19+
20+
# extending the previous maximum product subarray to include the current element.
21+
local_max_product * current,
22+
23+
# if the current element is negative, multiplying it by the previous minimum product subarray
24+
# (which could be a large negative number) might result in a large positive number,
25+
# thus becoming the new maximum product.
26+
min_product * current,
27+
)
28+
min_product = min(
29+
current, local_max_product * current, min_product * current
30+
)
31+
local_max_product = temp_max
32+
33+
global_max_product = max(global_max_product, local_max_product)
34+
35+
return global_max_product

0 commit comments

Comments
 (0)