[LeetCode] 628. 三个数的最大乘积 ☆

描述

给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。

示例 1:

输入: [1,2,3]
输出: 6
示例 2:

输入: [1,2,3,4]
输出: 24
注意:

给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。

解析

3个最大值的可能情况:3个正数   2个负数+1个正数。

代码

public static int maximumProduct(int[] nums) {
        if (null == nums || nums.length <= 0) {
            return Integer.MIN_VALUE;
        } else if (nums.length == 3) {
            return nums[0] * nums[1] * nums[2];
        }
        //存放3个最大值,2个最小值。最大值初始值为Integer.MIN_VALUE,最小值初始值为Integer.MAX_VALUE
        int max1 = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;
        int max3 = Integer.MIN_VALUE;
        int min1 = Integer.MAX_VALUE;
        int min2 = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            //最大值
            if (nums[i] > max1) {
                max3 = max2;
                max2 = max1;
                max1 = nums[i];
            } else if (nums[i] > max2) {
                max3 = max2;
                max2 = nums[i];
            } else if (nums[i] > max3) {
                max3 = nums[i];
            }
            //最小值
            if (nums[i] < min1) {
                min2 = min1;
                min1 = nums[i];
            } else if (nums[i] < min2) {
                min2 = nums[i];
            }
        }
        return Math.max(max1 * max2 * max3, max1 * min1 * min2);
    }

猜你喜欢

转载自www.cnblogs.com/fanguangdexiaoyuer/p/12173072.html