LC 628. Maximum Product of Three Numbers

Nilanjan Deb · April 1, 2020

I solved this problem using a simple logic. The algorithm is if I sort the array and find the product of last three elemnts it will be maximum. But in constraints elements of nums array may be negetive and we know that product of two negetive numbers is positive so here raise a another situation in which we got maximum value. So I take this situation into account and compare with the result which I got multiplying last three numbers. (Here time complexity raise due to std::sort function)

This is my CPP solution.

class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        int n = nums.size();
        if(n<3){
            return 0;
        }
        sort(nums.begin(),nums.end());
        int cnt_neg = 0;
        for(int i=0;i<n;i++){
            if(nums[i]<0){
                cnt_neg++;
            }
        }
        int mx_mult = nums[n-1]*nums[n-2]*nums[n-3];
        if(cnt_neg>=2){
            mx_mult = max(nums[0]*nums[1]*nums[n-1],mx_mult);
        }
        return mx_mult;
    }
};

Time Complexity O(n*log(n)); Space Complexity O(1);



Dicussion Forum