152 - Maximum Product Subarray
Written on October 21, 2015
Tweet
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
class Solution:
def maxProduct(self, nums: List[int]) -> int:
if not nums:
return 0
ret = min_val = max_val = nums[0]
for num in nums[1:]:
candidates = [min_val * num, max_val * num, num]
min_val, max_val = min(candidates), max(candidates)
ret = max(ret, max_val)
return ret