Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
It is guaranteed that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
动态转移方程
maxn = max(nums[i], nums[i] * maxn)
minn = min(nums[i], nums[i] * minn)
边界条件
maxn = 1, minn = 1
代码
class Solution {
public:
int maxProduct(vector<int>& nums) {
int len = nums.size();
int maxn = 1, minn = 1;
int res = nums[0];
for(int i = 0; i < len; i++)
{
if(nums[i] < 0)
swap(maxn, minn);
maxn = max(nums[i], nums[i] * maxn);
minn = min(nums[i], nums[i] * minn);
if(res < maxn)
res = maxn;
}
return res;
}
};