152. Maximum Product Subarray
Problem description:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
Solution:
Use a res
variable to denote the maximum result to return. In addition, two variables imin
and imax
for to store current maximum value and current minimum value. Why do we need to store the minimum value? The smallest product, which is the largest in the negative sense could become the maximum when being multiplied by a negative number.
1 | class Solution: |
1 | class Solution { |
time complexity: $O(n)$
reference:
https://goo.gl/Eu7Vb4
https://goo.gl/fDPzc1