LeetCode 152. Maximum Product Subarray
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.
class Solution {
public:
const int inf = -9999999;
int maxProduct(vector<int>& nums) {
int ans = inf;
vector<int> postive(nums.size()+1, inf);
vector<int> negtive(nums.size()+1, inf);
for(int i=0; i<nums.size(); i++){
if( nums[i]<0){
postive[i+1] = negtive[i] == inf ? inf : negtive[i] * nums[i];
negtive[i+1] = postive[i] == inf ? nums[i] : min( nums[i], nums[i]*postive[i]);
}else{
postive[i+1] = postive[i] == inf ? nums[i] : max( nums[i], nums[i]*postive[i]);
negtive[i+1] = negtive[i] == inf ? inf : negtive[i] * nums[i];
}
ans = max( ans ,max(postive[i+1], negtive[i+1]));
}
return ans;
}
};