Skip to content

Commit 6cfbe3f

Browse files
committed
solve: maximumProductSubarray
1 parent ac55b4c commit 6cfbe3f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

maximum-product-subarray/yolophg.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time Complexity: O(N) - just one pass through the array, so it's linear time.
2+
# Space Complexity: O(1) - no extra arrays, just a few variables.
3+
4+
class Solution:
5+
def maxProduct(self, nums: List[int]) -> int:
6+
# tracking max product from both ends
7+
prefix_product, suffix_product = 1, 1
8+
# start with the biggest single number
9+
max_product = max(nums)
10+
11+
for i in range(len(nums)):
12+
# move forward, multiplying
13+
prefix_product *= nums[i]
14+
# move backward, multiplying
15+
suffix_product *= nums[len(nums) - i - 1]
16+
# update max product
17+
max_product = max(max_product, prefix_product, suffix_product)
18+
19+
# if hit zero, reset to 1 (zero kills the product chain)
20+
if prefix_product == 0:
21+
prefix_product = 1
22+
if suffix_product == 0:
23+
suffix_product = 1
24+
25+
return max_product

0 commit comments

Comments
 (0)