LeetCode628. Maximum Product of Three Numbers

版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/88094702

628. Maximum Product of Three Numbers

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:

The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.


题目nums中三个数的最大乘积。

思路:先排序。因为nums中可能存在负数,那么三个数的最大乘积在以下两种情况中的较大值:最后三个数的乘积;前两个负数和最后一个数的乘积。其实我们可以不需要对nums排序,只需要找到最小的两个数和最大的三个数即可,具体可参考Approach #3 Single Scan [Accepted]

工程代码下载

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

猜你喜欢

转载自blog.csdn.net/grllery/article/details/88094702