C++ One-pass O(n) time O(1) space solution, 10 lines, 3ms


  • 0
    A

    183 / 183 test cases passed
    Status: Accepted
    Runtime: 3 ms

    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            int e = nums.size(), n = 0, pb = 0, p = 0, m = nums[0];
            for (uint i = 0; i < e; i++) {
                if (nums[i]) n++;
                else pb = n = 0;
                if (p < 0 && !pb && n > 1) pb = p;
                p = n > 1 ? p * nums[i] : nums[i];
                if ((i+1 == e || !nums[i+1]) && p < 0 && pb) p /= pb;
                if (p > m) m = p;
            }
            return m;
        }
    };
    

Log in to reply
 

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