乘积最大子数组
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
if (n == 1)
return nums[0];
vector<double> f(n, 1), g(n, 1);
f[0] = g[0] = nums[0];
double res = nums[0];
for (int i = 1; i < n; i++) {
f[i] = max(static_cast<double>(nums[i]), max(f[i - 1] * nums[i], g[i - 1] * nums[i]));
g[i] = min(static_cast<double>(nums[i]), min(f[i - 1] * nums[i], g[i - 1] * nums[i]));
res = max(res, max(f[i], g[i]));
}
return static_cast<int>(res);
}
};
1567. 乘积为正数的最长子数组长度
class Solution {
public:
int getMaxLen(vector<int>& nums) {
int n = nums.size();
vector<int> f(n + 1, 0), g(n + 1, 0);
int res = INT_MIN;
for(int i = 1; i < n + 1; i++)
{
if(nums[i - 1] > 0)
{
f[i] = f[i - 1] + 1;
g[i] = g[i - 1] == 0 ? 0 : g[i - 1] + 1;
}
else if(nums[i - 1] < 0)
{
f[i] = g[i - 1] == 0 ? 0 : g[i - 1] + 1;
g[i] = f[i - 1] + 1;
}
res = max(res, f[i]);
}
return res;
}
};