Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Approach #1: Math. [C++]
class Solution {
public:
int maxProduct(vector<int>& nums) {
int size = nums.size();
if (size == 0) return size;
int ans = nums[0];
int curmax = nums[0];
int curmin = nums[0];
for (int i = 1; i < size; ++i) {
int nextmax = curmax * nums[i];
int nextmin = curmin * nums[i];
curmax = max(nums[i], max(nextmax, nextmin));
curmin = min(nums[i], min(nextmax, nextmin));
ans = max(ans, max(curmax, curmin));
}
return ans;
}
};
Analysis:
Because nums is an integer array, so nums[i] > 1. In this travel's every step(++i) we find the curmin and curmax and ans from 0 to current index(i), curmin can become curmax and curmax can become curmin, if both curmin and curmax are less than 0, nums[i] > 0 so nums[i] is the curmax.