4-line C++ Solution, with explaination

  • 0

    The Idea is really simple: Case1: all positive numbers - the greatest number is the multiple of greatest three numbers. Case 2: with negative numbers - the multiple of the smallest two negative numbers and the greatest positive numbers.

    So the solution is like max(case1, case2) plus considering bases cases.


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

Log in to reply

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