考虑数组中的正负数。
解题思路:
排序:排序之后取值比较
线性扫描:循环一遍计算比较
复杂度以及具体逻辑看代码:
import java.util.Arrays;
public class MaxProduct {
public static void main(String[] args) {
System.out.println();
}
//排序后输出最大值 Nlog(n)
public static int sort(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]);
}
//线性扫描 O(n)
public static int getMaxMin(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 x:nums){
if(x<min1){
min2=min1;
min1 = x;
} else if(x<min2){
min2=x;
}
if(x>max1){
max3=max2;
max2=max1;
max1=x;
}else if(x>max2){
max3=max2;
max2=x;
}else if(x>max3){
max3=x;
}
}
return Math.max(min1*min2*max1,max1*max2*max3);
}
}