Leetcode 628 Solution

This article provides solution to leetcode question 628 (maximum-product-of-three-numbers)

https://leetcode.com/problems/maximum-product-of-three-numbers

Solution

class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        int max1 = INT_MIN;
        int max2 = INT_MIN;
        int max3 = INT_MIN;

        for (auto num : nums)
        {
            if (num >= max1)
            {
                max3 = max2;
                max2 = max1;
                max1 = num;
            }
            else if (num >= max2)
            {
                max3 = max2;
                max2 = num;
            }
            else if (num >= max3)
                max3 = num;
        }

        int min1 = INT_MAX;
        int min2 = INT_MAX;
        for (auto num : nums)
        {
            if (num <= min1)
            {
                min2 = min1;
                min1 = num;
            }
            else if (num <= min2)
                min2 = num;
        }

        return max(max1 * max2 * max3, max1 * min1 * min2);
    }
};