题目链接
class Solution {
// 1.排序+分情况 取最大值 11ms,71.55%
public int maximumProduct1(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
return Math.max(nums[0]*nums[1]*nums[n-1],nums[n-1]*nums[n-2]*nums[n-3]);
}
// 2.线性。 一次性找到上面排序的五个值。。。 2ms,99.57%
public int maximumProduct(int[] nums) {
int min1 = Integer.MAX_VALUE,min2 = Integer.MAX_VALUE;
int max1 = Integer.MIN_VALUE,max2 = Integer.MIN_VALUE,max3 = Integer.MIN_VALUE;
for(int n : nums) {
if(n < min1) {
min2 = min1;
min1 = n;
} else if(n < min2) {
min2 = n;
}
if(n > max1) {
max3 = max2;
max2 = max1;
max1 = n;
} else if(n > max2) {
max3 = max2;
max2 = n;
} else if(n > max3) {
max3 = n;
}
}
// System.out.println(min1 + " " + min2 + " " + max3 + " " + max2 + " " + max1);
// 比较两个乘积的大小。
return Math.max(min1*min2*max1, max1*max2*max3);
}
}