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
Note:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.
题意:给定一个数组,要求得到数组中三个数的最大乘积;
解法:要得到三个数乘积的最大值,那么这三个数要么全是正数,要么一个正数和两个负数;因此,我们只需要对数组进行排序后,计算数组首部两个负数(如果存在的话)和最后一个数的乘积,计算机数组尾部三个数的乘积,返回这两种情况下的最大值;
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int mulResult1 = nums[0] * nums[1] * nums[nums.length-1];
int mulResult2 = nums[nums.length-1] * nums[nums.length-2] * nums[nums.length-3];
return mulResult1 > mulResult2 ? mulResult1 : mulResult2;
}
}