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.
解题思路:
从简单情况扩展,负数有且仅出现1次,则数列最大乘积为负数左序列和右序列的最大乘积;负数出现单数次数,则数列最大乘积为其中2n个负数及其延伸的基数列;负数出现双数次数,则数列最大乘积为所有数字总乘积。
那么设back为从左乘起数列乘积,front为从右乘起的数列乘积,编列数列,比较取得最大值。题目较为简单,直接列代码。
int maxProduct(vector<int>& nums) {
int n = nums.size() - 1;
int front = 1, back = 1;
int res = INT_MIN, cur = INT_MIN;
for(int i = 0; i <= n; i++){
front *= nums[i];
back *= nums[n-i];
cur = max(front, back);
res = max(res, cur);
if(front == 0)front = 1;
if(back == 0)back = 1;
}
return res;
}