1567. Maximum Length of Subarray With Positive Product
Solutions
class Solution {
public:
int getMaxLen(vector<int>& nums) {
nums.push_back(0);
int n = nums.size(), res = 0, INF = 0x3f3f3f3f;
int neg = 0, fneg = INF, lneg = -INF;
for (int i = -1, j = 0; j < n; j++) {
if (nums[j] == 0) {
// meet a zero, try to remove the first negative or the last negative number.
int len = j - i - 1;
if (neg & 1) {
res = max(res, len - (fneg - i));
res = max(res, len - (j - lneg));
}
else
res = max(res, len);
i = j; neg = 0;
fneg = INF; lneg = -INF;
}
else if (nums[j] < 0) {
neg++;
fneg = min(fneg, j);
lneg = max(lneg, j);
}
}
return res;
}
};Last updated