题解 | #三个数的最大乘积#
三个数的最大乘积
http://www.nowcoder.com/practice/8ae05c2913fe438b8b14f3968f64fc0b
import java.util.*; public class Solution { /** * 最大乘积 * @param A int整型一维数组 * @return long长整型 */ public long solve (int[] A) { // write code here long result = 0L; if(A.length == 3){ result = A[0] * A[1] * A[2]; return result; } ArrayList<Long> neg = new ArrayList<>(); ArrayList<Long> pos = new ArrayList<>(); long result1 = 0L; long result2 = 0L; for(int i = 0; i < A.length; i++){ if(A[i] < 0){ neg.add((long)A[i]); } else{ pos.add((long)A[i]); } } Collections.sort(neg, new Comparator<Long>(){ @Override public int compare(Long num1, Long num2){ if(num1 > num2){ return 1; } else{ return -1; } } }); Collections.sort(pos, new Comparator<Long>(){ @Override public int compare(Long num1, Long num2){ if(num1 > num2){ return 1; } else{ return -1; } } }); if (neg.size() < 2){ result = pos.get(pos.size() - 1) * pos.get(pos.size() - 2) * pos.get(pos.size() - 3); return result; } else if(pos.size() == 2){ result = pos.get(pos.size() - 1) * neg.get(0) * neg.get(1); return result; } else if (pos.size() == 0) { result = neg.get(0) * neg.get(1) * neg.get(2); return result; } else{ result1 = pos.get(pos.size() - 1) * pos.get(pos.size() - 2) * pos.get(pos.size() - 3); result2 = pos.get(pos.size() - 1) * neg.get(0) * neg.get(1); if((result1 - result2) >= 0){ return result1; } else{ return result2; } } } }