Maximum Product Subarray
Link Maximum Product Subarray
Type: Array/Dynamic Programming
Difficulty: Medium
How to think of the problem
We have to consider a few things:
- Negative numbers affect the output
- 0's will destroy us
- a number can be a max by itself
result
is initialized to the max of the array
we then track our current minimum and current maximum.
we need a temp variable since we reassign curMax prior to calculating curMin
for each item, we take the max of n, n*curMax and n*curMin
we then take the max of result, curMax, and curMin and assign it to res
Solution
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = max(nums) #initialized to the max value of nums
curMin, curMax = 1,1
for n in nums:
temp = curMax * n
curMax = max(n * curMax, n * curMin, n)
curMin = min(n * curMin, temp, n)
res = max(res, curMax, curMin)
return res