O(n) and O(1) solution c++ simple


  • 0
    V
    int maxProduct(vector<int>& nums) {
            int len = nums.size();
            if (len == 0)
            return 0;
            if (len == 1)
            return nums[0];
            int pos = -1;
            int neg = 1;
            int maxi = nums[0];
            for (int i = 0 ; i < len ; i++) {
                int x = nums[i];
                if (x > 0) {
                    pos = max(pos*x,x);
                    neg = min(neg*x , 1);
                    if (maxi < pos)
                        maxi = pos;
                }
                else if (x==0) {
                    pos = -1;
                    neg = 1;
                    if (maxi < 0)
                    maxi=0;
                }
                else {
                    int tmp = pos;
                    pos = max (neg*x , -1);
                    neg = min(tmp*x,x);
                    if (maxi < pos)
                        maxi = pos;
                }
            }
            return maxi;
        }

Log in to reply
 

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