Sunday, August 30, 2020

Leetcode 1567. Maximum Length of Subarray With Positive Product

https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/description/



Notes:

This question can be solved by greedy.

1): If meets with zero, we need to start the counting again from the zero position;
2): If meets with a positive value, the product will have the same sign as the previous product;
3): If meets with a negative value, then the product will have a opposite sign as the previous product.

If the updated product is positive, then we need to update the maxLen with the most current zero position;
If the updated product is negative, then we need to update the maxLen with the most current negative position.

So the code below:

class Solution {
public:
    int getMaxLen(vector<int>& nums) {
        int n = nums.size(), res = 0;
        for(int i = 0; i < n; ) {
            if(nums[i] == 0) {++i; continue;}
            int j = i, mostLeftNegativeIdx = j-1, p = 1;
            while(i < n && nums[i] != 0) {
                if(nums[i] < 0) p = -p;
                if(p > 0) res = max(res, i - j + 1);
                else {
                    if(mostLeftNegativeIdx > j-1) res = max(res, i - mostLeftNegativeIdx);
                    else mostLeftNegativeIdx = i;
                }
                ++i;
            }
        }
        return res;
    }
};

No comments:

Post a Comment