Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
1. 先对数组从小到大进行排序
2. 分类讨论
情况分析:
- 第一个数是正数:直接最后三个数的乘积
- 序列有正有负数,最终乘积有正有负数。
class Solution {
public int maximumProduct(int[] nums){
Arrays.sort(nums);
int len = nums.length;
if (nums[0]>0) return nums[len-3]*nums[len-2]*nums[len-1];
return nums[0]*nums[1]*nums[len-1] > nums[len-3]*nums[len-2]*nums[len-1]?nums[0]*nums[1]*nums[len-1]:nums[len-3]*nums[len-2]*nums[len-1];
}
}