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,10^ 4] 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.
给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入: [1,2,3] 输出: 6
示例 2:
输入: [1,2,3,4] 输出: 24
注意:
- 给定的整型数组长度范围是[3,10^4],数组中所有的元素范围是[-1000, 1000]。
- 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
题解:给定一个数组,求其中的任意三个元素乘积构成的最大的数。拿到这道题,lz就想到先对这个数组进行从小到大排序,然后再挑选。但是仔细一想,有一种非常简单的方式,因为已经对该数组从小到大排序了,那么不出意外,该最大的三个数只可能出现在该数组的前3个数;最后的3个数;或者是前两个数,和最后一个数;或者是前一个数,后两个数。因为有可能该数组中的元素存在负数,那么有可能前几个数相乘有可能会最大;但是最终都不会逃过上述这四种情况。
public int maximumProduct(int[] nums)
{
Arrays.sort(nums);
int s = nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3];
s = Math.max(s,nums[nums.length - 1] * nums[nums.length - 2] * nums[0]);
s = Math.max(s,nums[nums.length - 1] * nums[1] * nums[0]);
s = Math.max(s,nums[2] * nums[1] * nums[0]);
return s;
}
代码非常简单,但是理解却非常难!深入理解后,就能做出最简单的解法。