We split the vector into several segments based on the location of zero, and then calculate the max product for each segment (notice that the end one should always be end of segment). The max product for segment is calculated in getProd, and this is done by first counting negative numbers, if there are even numbers we multiply all numbers to get the largest product, if there are odd number of negative value, we end before the last negative value (prod1) or start after the first negative value (prod2).

In the end, if the max prod of segments is negative and there are zer o in the vector, maximum is zero then.

Code

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int zeroCnt = count_if(nums.begin(), nums.end(), [](int n){return n == 0;});

        int maxProduct = INT_MIN;
        vector<int> seg;
        int n = nums.size();
        for(int i = 0 ; i <= n ; ++i) {
            if(i == n || nums[i] == 0) {
                maxProduct = max(maxProduct, getProd(seg));
                seg.clear();
            } else {
                seg.push_back(nums[i]);
            }
        }

        if (maxProduct < 0 && zeroCnt > 0) return 0;
        return maxProduct;
    }

    int getProd(const vector<int>& seg) {
        int n = seg.size();
        if(n == 0) return INT_MIN;
        int negCnt = count_if(seg.begin(), seg.end(), [](int n){return n < 0;});
        if(negCnt == 1 && n == 1) return seg[0];

        if (negCnt % 2 == 0) {
            int prod = 1;
            for(int i = 0 ; i < n ; ++i) prod *= seg[i];
            return prod;
        }
        int curNegCnt = 0;
        int prod1 = 1;
        for(int i = 0 ; i < n ; ++i) {
            if(seg[i] < 0) {
                ++curNegCnt;
                if(curNegCnt == negCnt) break;
            }
            prod1 *= seg[i];
        }

        int prod2 = 1;
        bool first = false;
        for(int i = 0 ; i < n ; ++i) {
            if(!first && seg[i] < 0) {
                first = true;
                prod2 = 1;
            } else {
                prod2 *= seg[i];
            }
        }

        return max(prod1, prod2);
    }
};