三个数的最大乘积

题目:

 

 

 

思路:

本题难点:第一,三个数相乘有可能会达到数值的极限,应用long,其次,结果为两种,最大的三个数相乘或者最大的正数与最小的两个负数相乘。
 

代码示例:

public class Solution2 {
    public static void main(String[] args) {
        int[] A = {3472, 7789, 7955, -7098, -9281, 6101, 5051, 7778, 3090, 7423, -7151, 5652, 1595, -8094, 677, -8324, 8347, -2482, 9313, -9338, -3157, 8559, 6945, 3618, 3087, 121, -8468, 3225, 1356, 6939, 2799, -7231, -6309, -5453, 633, -8689, -4776, 2714, -2743, -1409, 5918, -3333, 1803, 8330, -2206, -6117, -4486, -7903, -4375, -3739, 2897, 8056, -5864, -522, 7451, -4541, -2813, 5790, -532, -6517, 925};
        System.out.println(solve(A));
    }
 
    /**
     * 最大乘积
     *
     * @param A int整型一维数组
     * @return long长整型
     */
    public static long solve(int[] A) {
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
        for (int i = 0; i < A.length; i++) {
            if (A[i] < min1) {
                min2 = min1;
                min1 = A[i];
            } else if (A[i] < min2) {
                min2 = A[i];
            }
 
            if (A[i] > max1) {
                max3 = max2;
                max2 = max1;
                max1 = A[i];
            } else if (A[i] > max2) {
                max3 = max2;
                max2 = A[i];
            } else if (A[i] > max3) {
                max3 = A[i];
            }
        }
        return Math.max((long) max1 * max2 * max3, (long) max1 * min1 * min2);
    }
}
 
posted @ 2021-01-13 18:38  忧愁的chafry  阅读(189)  评论(0编辑  收藏  举报