628.Maximum Product of Three Numbers
题目链接:https://leetcode.com/problems/maximum-product-of-three-numbers/description/
题目大意:从一个数组中选取三个数,使其乘积最大。
法一:直接排序后取最大值即可。代码如下(耗时30ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public int maximumProduct(int[] nums) { 2 Arrays.sort(nums); 3 int mi1 = nums[0]; 4 int mi2 = nums[1]; 5 int res = 0; 6 //取左边两个负数和右边最大正数 7 if(nums[nums.length - 2] * nums[nums.length - 3] < mi1 * mi2) { 8 res = mi1 * mi2 * nums[nums.length - 1]; 9 } 10 //取右边最大的三个正数 11 else { 12 res = nums[nums.length - 2] * nums[nums.length - 3] * nums[nums.length - 1]; 13 } 14 return res; 15 }