C++ O(1) space O(n) time solution with swap()

  • 0
    class Solution {
        int maximumProduct(vector<int>& nums) {
            int max1=INT_MIN,max2=INT_MIN,max3=INT_MIN;
            int min1=INT_MAX,min2=INT_MAX;
            for(auto &n : nums) {
                if (n>max3) max3=n;
                if (max3>max2) swap(max2,max3);
                if (max2>max1) swap(max1,max2);
                if (n<min2) min2 = n;
                if (min2<min1) swap(min1,min2);
            return max(max1*max2*max3, max1*min1*min2);

Log in to reply

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