628. Maximum Product of Three Numbers
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.
就是给出一个数组,找出数组中的三个数使得他们的乘积最大,注意,数组中的元素可能为负数。
思路:先排序,然后分两种情况
①都为正数的时候,排序后的数组最后三个数乘积最大
②有负数的时候,排序后的数组前两个元素和最后一个元素的乘积可能为最大,因为有负数,则一定要负负得正才可能使得乘积为正数,所以要取前两个元素
public class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);//排序
int n = nums.length;//n为数组长度
int s = nums[n-1]*nums[n-2]*nums[n-3];//都为正数的情况
s = Math.max(s,nums[n-1]*nums[1]*nums[0]);//都为正数和有负数的比较
return s;
}
}