C++ 8ms, O(n) time, O(1) space


  • 0
    class Solution {
    public:
    int maxProduct(vector<int>& nums) {
        if (nums.empty()) return 1;
        if (nums.size()==1) return nums[0];
        int k=nums.size();
        int pos,neg;
        pos = nums[0]>0?nums[0]:0;
        neg = nums[0]<0?nums[0]:0;
        int maxP=pos;
        for (int i=1;i<k;i++){
            if (nums[i]==0){
                pos=0;neg=0;
            }
            else if(nums[i]>0){
                pos = max(nums[i],nums[i]*pos);
                neg = min(0,nums[i]*neg);
            }
            else{
                int temp=pos;
                pos = max(0,nums[i]*neg);
                neg = min(nums[i],nums[i]*temp);          
            }
            maxP = maxP>pos?maxP:pos;
        }
        return maxP;
    }
    };

Log in to reply
 

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