编程语言
首页 > 编程语言> > Leetcode第628题 三个数的最大乘积C++解法

Leetcode第628题 三个数的最大乘积C++解法

作者:互联网

class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        int high1=-1001,high2=-1001,high3=-1001,low1=1001,low2=1001;   
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>=high1)
                {high3=high2,high2=high1,high1=nums[i];}
            else if(nums[i]>=high2)
                {high3=high2,high2=nums[i];}
            else if(nums[i]>=high3)
                high3=nums[i];
            if(nums[i]<=low1)
                {low2=low1,low1=nums[i];}
            else if(nums[i]<=low2)
            low2=nums[i];                         
        }
        if(low2<0&&high1>0)
        return low1*low2*high1;
        return high1*high2*high3;
    }
};
class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        int high1=-1001,high2=-1001,high3=-1001,low1=1001,low2=1001;   
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]>=high1)
                {high3=high2,high2=high1,high1=nums[i];}
            else if(nums[i]>=high2)
                {high3=high2,high2=nums[i];}
            else if(nums[i]>=high3)
                high3=nums[i];
            if(nums[i]<=low1)
                {low2=low1,low1=nums[i];}
            else if(nums[i]<=low2)
            low2=nums[i];                         
        }
        return max(low2*low1*high1,high1*high2*high3);
    }
};

标签:high2,nums,high1,high3,628,C++,low1,Leetcode,1001
来源: https://blog.csdn.net/meixingshi/article/details/112385410