Simple C++ solution 4ms


  • 2

    The idea is to record the first negative product (N) for later use. If current product (P) is negative, make it positive by dividing N. If P is zero, reset everything.

    int maxProduct(vector<int>& nums) {
        if( nums.empty() ) return 0;
        int neg = 0, product = 1, val, maxp = INT_MIN;
        for( int i : nums ) {
            product *= i;
            if( product < 0 ) {
                val = neg ? (product/neg) : i;
                if( !neg && i < 0 ) neg = product;
            } else if( product == 0 ) {
                product = 1;
                neg = val = 0;
            } else val = product;
            maxp = max( maxp, val );
        }
        return maxp;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.