public class MaxProduct {
public static int maxProduct(int[] arr) {
if (arr == null || arr.length < 2) {
return 0;
}
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
for (int num : arr) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2) {
min2 = num;
}
}
return Math.max(max1 * max2, min1 * min2);
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class MaxProductTest{
@Test
public void testMaxProduct1() {
// 正数和负数混合
int[] arr1 = {3, 5, -2, 8, -7};
assertEquals(40, MaxProduct.maxProduct(arr1)); // 8*5
}
@Test
public void testMaxProduct2() {
// 全负数
int[] arr2 = {-1, -4, -3, -2};
assertEquals(12, MaxProduct.maxProduct(arr2)); // -4*-3
}
@Test
public void testMaxProduct3() {
// 全正数
int[] arr3 = {1, 2, 3, 4};
assertEquals(12, MaxProduct.maxProduct(arr3)); // 4*3
}
@Test
public void testMaxProduct4() {
// 只有一个元素
int[] arr4 = {5};
assertEquals(0, MaxProduct.maxProduct(arr4));
}
@Test
public void testMaxProduct5() {
// 空数组
int[] arr5 = {};
assertEquals(0, MaxProduct.maxProduct(arr5));
}
}