要求时间复杂度:
,空间复杂度:
。
数据范围:
public long solve (int[] A) {
// write code here
int len=A.length;
Arrays.sort(A);
return Math.max((long)A[len-1]*A[len-2]*A[len-3] ,(long)A[len-1]*A[0]*A[1]);
} import java.util.*;
public class Solution {
/**
* 最大乘积
* @param A int整型一维数组
* @return long长整型
*/
public long solve (int[] A) {
// write code here
Arrays.sort(A);//排序,排序后取最小两个数和最大数的乘积与三个最大数相比取大者返回
long a=A[A.length-1];
long b=A[A.length-2];
long c=A[A.length-3];
long d=A[0];
long e=A[1];
if(a*b*c>a*d*e)
return a*b*c;
else
return a*d*e;
}
} public long solve (int[] A) {
// write code here
int fushu_count = 0; //出现负数的个数
int zhengshu_count = 0; //出现正数的个数
int zero_count = 0; //出现0的个数
int res_max = Integer.MIN_VALUE;
List<Integer> sortList = new ArrayList<Integer>();
for(int i : A){
sortList.add(i);
if(i < 0){
fushu_count ++;
}else if(i > 0 ){
zhengshu_count ++;
}else{
zero_count ++;
}
}
//进行排序
Collections.sort(sortList);
//有0 有正 有负 此时可能最大的是这几种组合:
//1、最前面的两个和最后一个
//2、最后面的三个
//3、0
if(fushu_count >0 || zhengshu_count >0 || zhengshu_count >0){
//全是负数
if(zhengshu_count == 0 && zero_count == 0 && fushu_count > 0){
long max6 = (long)sortList.get(sortList.size() - 1)
* sortList.get(sortList.size() - 2)
* sortList.get(sortList.size() - 3);
return max6;
}
//两负一正
long max1 = (long)sortList.get(sortList.size() - 1)
* sortList.get (0)
* sortList.get(1);
//全正
long max2 = (long)sortList.get(sortList.size() - 1)
* sortList.get(sortList.size() - 2)
* sortList.get(sortList.size() - 3);
//例如那种-1 2 2 0
long max3 = 0;
long max4 = Math.max(max1,max2);
long max5 = Math.max(max4,max3);
return max5;
}
return 0;
} import java.util.*;
public class Solution {
public long solve (int[] A) {
Arrays.sort(A);
int len = A.length-1;
return Math.max((long)A[len]*A[len-1]*A[len-2],(long)A[0]*A[1]*A[len]);
}
} public long solve (int[] A) {
// write code here
int length = A.length;
ArrayList<Long> a=new ArrayList<>(length);
for (int i : A) {
a.add((long) i);
}
Collections.sort(a);
System.out.println(a);
long MaxOne=a.get(length-1)*a.get(length-2)*a.get(length-3);
long MaxTwo=a.get(0)*a.get(1)*a.get(length-1);
return (MaxOne>MaxTwo)?MaxOne:MaxTwo;
} import java.util.*;
public class Solution {
/**
* 最大乘积
* @param A int整型一维数组
* @return long长整型
*/
public long solve (int[] A) {
// write code here
int max1=Integer.MIN_VALUE,max2=Integer.MIN_VALUE,max3=Integer.MIN_VALUE;
int min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE;
for(int num:A){
if(num>max1){
max3=max2;
max2=max1;
max1=num;
} else if(num>max2){
max3=max2;
max2=num;
} else if(num>max3) max3=num;
if(num<min1){
min2=min1;
min1=num;
} else if(num<min2) min2=num;
}
return Math.max((long)max1*max2*max3,(long)max1*min1*min2);
}
}