C++ solution, 4ms, with comment


  • 1
    N
    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            int maxProd = nums[0];
            
            // simple case
            if(nums.size()==1) return maxProd;
            
            // other cases
            /* adding a one in front of the sequence does not change the solution,
               so let's just assume we already read a one. */
            int first_neg = 1, run = 1;
            for(int i=0; i<nums.size(); i++){
                // read a non-zero integer
                if(nums[i]){
                    run *= nums[i];
                    // negative running product
                    if(run<0){
                        if(first_neg>0) first_neg = run; // first negative running product
                        else maxProd = max(maxProd,run/first_neg);
                    }
                    // positive running product
                    else maxProd = max(maxProd,run);
                }
                // restart when reading a zero
                else{
                    maxProd = max(maxProd,0);
                    first_neg = 1;
                    run = 1;
                }
            }
            return maxProd;
        }
    };

Log in to reply
 

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