C++ O(n) solution


  • 0
    B

    class Solution {
    public:
    int maximumProduct(vector<int>& nums) {
    int size = nums.size();
    if (size < 2)
    return 0;
    int top_max = INT_MIN, sec_max = INT_MIN, thi_max = INT_MIN, neg_min = 0, neg_max = 0;

        for (int i = 0; i < size; i++) {
            int n = nums[i];
            if (n >= top_max) {
                thi_max = sec_max;
                sec_max = top_max;
                top_max = n;
            } else if (n >= sec_max) {
                thi_max = sec_max;
                sec_max = n;
            } else if (n > thi_max)
                thi_max = n;
    
            if (n <= neg_min) {
                neg_max = neg_min;
                neg_min = n;
            }else if (n < neg_max)
                neg_max = n;
        }
        if (neg_max)
            return max(top_max * sec_max * thi_max, top_max * neg_min * neg_max);
        else
            return top_max * sec_max * thi_max;
        
        return top_max;
    }
    

    };


Log in to reply
 

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