数组中三个数最大乘积 一 全是正数 二 全是负数 这个的话排序后 选择后三个数就是最大乘积数 三是 有正有负 那么 应该选择排序后的前两个负数的和最后的正数的乘积
排序后求解
public static int totalSum(int [] nums)
{
Arrays.sort(nums);
int len = nums.length;
return Math.max(nums[0]*nums[1]*nums[len-1],nums[len-1]*nums[len-2]*nums[len-3]);
}
线性扫描法求解
public static int trueSort(int [] nums)
{
int min1 = Integer.MAX_VALUE,min2 = Integer.MIN_VALUE;
int max1 = Integer.MIN_VALUE,max2 = Integer.MIN_VALUE,max3 = Integer.MIN_VALUE;
for(int i =0;i<nums.length;i++)
{
int x = nums[i];
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);
}