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
解题思路:
直接先排序,后找相乘最大。注意这里要考虑负数的情况!!因为三个数相乘最大,有两种情况:+++,+--,而--的两负数必然是最小的负数,它们相乘才可能是最大的正数,所以比较这两种情况的大小,谁大返回谁即可。
class Solution { public: /** * @param nums: an integer array * @return: the maximum product */ int maximumProduct(vector<int> &nums) { // Write your code here sort(nums.begin(),nums.end()); int n = nums.size()-1; int s = max(nums[n]*nums[n-1]*nums[n-2] , nums[n]*nums[0]*nums[1]); return s; } };