LeetCode 628. Maximum Product of Three Numbers

LeetCode 628. Maximum Product of Three Numbers

Description:

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


分析:

这道题很简单,先按从小到大排序,考虑后三个数的乘积、前两个数(负数)和最后一个数的乘积,这两个乘积孰大孰小即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int size = nums.size();
int temp1 = nums[size - 1] * nums[size - 2] * nums[size - 3];
int temp2 = nums[0] * nums[1] * nums[size - 1];
return temp1 > temp2 ? temp1 : temp2;
}
};
------本文结束感谢阅读------