152. Maximum Product Subarray
https://leetcode.com/problems/maximum-product-subarray/description/
It is a DP problem. Similar to 53.
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
Solution:
DP thought:
- use two slot to cache the max and the min products of the subarray that ends with current pointer.
- at each position, each time there are three possible numbers to choose from:
- current number
- current number X max product of last position
- current number X min product of last position
- so take the min and max of the three options to be current minP and maxP of current postion
1 | class Solution: |