【LeetCode】628. Maximum Product of Three Numbers

来源:互联网 发布:航信开票软件 编辑:程序博客网 时间:2024/06/05 19:39

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

题目是求三个数的最大乘积。
如果直接暴力是O(n3)时间复杂度,不可取。
仔细思考可以发现,如果数组都是正数,那么最大的乘积肯定是最大的三个数相乘。
如果考虑负数的情况,两个负数相乘为正,那么最大的值就是最小的两个负数加上最大的正数。
如果都是负数的话,最大乘积也是最大的三个数相乘。

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