Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
给出一个数组,找出其中3个数,使乘积最大
思路:
假如有两个数,乘积最大的是两个最大正数的积或者两个最小负数的积
那么3个数的情况下,最大乘积的即为最大的数 与 其余两个数的最大乘积 的积
这时需要找出数组中最大的数 和 其余两个最大的数和最小的数
可对数组排序,或者直接找到最大的三个数和最小的两个数
这里用排序
public int maximumProduct(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int n = nums.length;
int max1 = nums[0] * nums[1] * nums[n-1];
int max2 = nums[n-3] * nums[n-2] * nums[n-1];
return Math.max(max1, max2);
}