实现该算法主要思想是,
1.两个负数与与一个正数相乘2.全为最大正数相乘得到最大值
下面用算法实现,时间复杂度为O(n),下面用java实现,不过有一些为0的情况排除下可以,还有一些整形过大可以变为long型,这边不做累赘。
package com.meituan.test;
public class Test {
public static void main(String[] args) {
int[] arr = { -10, -1, 0, 2, 34, 1, 10, 8, 9 };
getMax(arr);
}
public static void getMax(int[] arr) {
int max = 1, second_max = 1, third_max = 1;
int min = 1, second_min = 1;
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
third_max = second_max;
second_max = max;
max = arr[i];
} else if (second_max < arr[i]) {
third_max = second_max;
second_max = arr[i];
} else if (third_max < arr[i]) {
third_max = arr[i];
} else if (arr[i] < min) {
second_min = min;
min = arr[i];
} else if (arr[i] < second_min) {
second_min = arr[i];
}
}
int max1=max*second_max*third_max;
int max2=max*second_min*min;
if(max1>=max2){
System.out.println("max:"+max+" second_max:"+second_max+" third_max:"+third_max+" result:"+max1);
}else{
System.out.println("max:"+max+" second_min:"+second_min+" min:"+min+" result:"+max2);
}
}
}
结果:
max:34
second_max:10 third_max:9
result:3060