From e2b43bd264cbb41044401c5504abbbaced72278b Mon Sep 17 00:00:00 2001 From: KyrieJ95 Date: Sun, 8 Sep 2024 01:04:21 +0900 Subject: [PATCH] Add maximum-product-subarray solution --- maximum-product-subarray/joon.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 maximum-product-subarray/joon.py diff --git a/maximum-product-subarray/joon.py b/maximum-product-subarray/joon.py new file mode 100644 index 000000000..8cc5a6a28 --- /dev/null +++ b/maximum-product-subarray/joon.py @@ -0,0 +1,18 @@ +from typing import List + + +class Solution: + # Time: O(n) + # Space: O(n) + def maxProduct(self, nums: List[int]) -> int: + maxProducts = [nums[0]] + minProducts = [nums[0]] + # Store all max/minProducts[i]: the max/min product of all subarrays that have nums[i] as the last element. + # Time: O(n) + # Space: O(n) + for num in nums[1:]: + newMaxProduct = max(maxProducts[-1] * num, minProducts[-1] * num, num) + newMinProduct = min(maxProducts[-1] * num, minProducts[-1] * num, num) + maxProducts.append(newMaxProduct) + minProducts.append(newMinProduct) + return max(maxProducts)