1567. Maximum Length of Subarray With Positive Product
T: O(n)
S: O(1)
class Solution {
public int getMaxLen(int[] nums) {
int n = nums.length;
int result = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
continue;
}
int j = i; // needs cal from i to j
int negativeCount = 0;
int k = -1;
while (j < n && nums[j] != 0) {
if (nums[j] < 0) {
negativeCount++;
}
if (negativeCount % 2 == 0) {
result = Math.max(result, j - i + 1);
} else if (k != -1) { // if has first negative index
result = Math.max(result, j - k);
}
if (k == -1 && nums[j] < 0) { // updated first negative one index
k = j;
}
j++;
}
i = j; // move to inner loop's end
}
return result;
}
}
/*
[0,1,-2,-3,-4]
skip 0
[1 - 2 -3]
[1-2 -3]
[1,-2,-3]
[-3, -4]
another subarray problem but this time how to find the left, right bound?
ex:
only want this subbarray, so skip 0
[ ]
[0,1,-2,-3,-4, 0, 1,2, 3]
i k j [ ]
another thing is to check in this [ ] =>
if the negative count is even: the ans is (j - i + 1)
if the negative count is odd: needs the first negative number's index k, skip this k, so use k+1 to i
=> ans is (j - (k+1) + 1) = (j-k)
T: O(n)
S: O(1)
*/
Last updated
Was this helpful?