最大子段乘积,我会最大子段和,但是这道题我不会用DP做,呜呜呜呜(我还有救吗)。
我用的方法比较简单暴力,时间复杂度O(n*n),最终OJ测试通过是356ms(其实还可以哈
遍历数组,当前数为正数时直接乘同时更新最大值;为0时则置1;为负数时,需要先判断在 剩下的数组元素且在0元素之前 的负数的个数,若不再有负数则置1,若有偶数个则一直连乘到除最后一个负数,若有奇数个则连乘到最后一个元素,最后更新最大值,同时将临时最大值置1
PS:这道题的数组元素都是整数,若是有-1~1之间的小数,我这个解法就不能用了QAQ,动归的那个解法依旧适用
题目:
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.
class Solution {
public:
int maxProduct(vector<int>& nums) {
int maxP = -1e9;
int p = 1;
int len = nums.size();
for(int i = 0; i < len; i++)
{
if(nums[i] > 0)
{
p *= nums[i];
maxP = max(maxP, p);
}
else if(nums[i] == 0)
{
maxP = max(maxP, 0);
p = 1;
}
else
{
int cnt0 = 0, j, jj;
int pp = p;
for(j = i + 1; j < len; j++)
{
if(nums[j] < 0)
{
cnt0++;
jj = j;
}
else if(nums[j] == 0) break;
}
if(cnt0 == 0)
{
maxP = max(maxP, nums[i]);
p = 1;
continue;
}
else if(cnt0 % 2 == 0) jj = jj - 1;
else jj = j - 1;
for(int k = i; k <= jj; k++)
pp *= nums[k];
maxP = max(maxP, pp);
p = 1;
}
}
return maxP;
}
};