Skip to content

Commit 5960de9

Browse files
authored
Merge pull request #3 from KyrieJ95/week4
Add maximum-product-subarray solution
2 parents b02425a + e2b43bd commit 5960de9

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

maximum-product-subarray/joon.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# Time: O(n)
6+
# Space: O(n)
7+
def maxProduct(self, nums: List[int]) -> int:
8+
maxProducts = [nums[0]]
9+
minProducts = [nums[0]]
10+
# Store all max/minProducts[i]: the max/min product of all subarrays that have nums[i] as the last element.
11+
# Time: O(n)
12+
# Space: O(n)
13+
for num in nums[1:]:
14+
newMaxProduct = max(maxProducts[-1] * num, minProducts[-1] * num, num)
15+
newMinProduct = min(maxProducts[-1] * num, minProducts[-1] * num, num)
16+
maxProducts.append(newMaxProduct)
17+
minProducts.append(newMinProduct)
18+
return max(maxProducts)

0 commit comments

Comments
 (0)