Leetcode Add to List 628. Maximum Product of Three Numbers

来源:互联网 发布:关于网络的论文 编辑:程序博客网 时间:2024/06/03 20:51

Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:

Input: [1,2,3]Output: 6

Example 2:

Input: [1,2,3,4]Output: 24

Note:

  1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
  2. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.  
思路:刚开始想的有点复杂,其实这道题就是判定最大的三个相乘和最小的两个(在均为负数)和最大的数相乘的最大值
一下是AC代码
class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        //1. 
        if(nums.size() < 3)
            return 0;
        //2. 对数组进行排序
        sort(nums.begin(),nums.end());
        int n = nums.size() - 1;
        int max_s = nums[n] * nums[n-1] * nums[n-2];
        max_s = max(max_s,nums[n] * nums[1] * nums[0]);
        return max_s;
    }
};
原创粉丝点击