628. 三个数的最大乘积——Java

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-three-numbers

方法一:排序

  1. 将数组进行升序排序,如果数组中所有的元素都是非负数,那么答案即为最后三个元素的乘积。

  2. 如果数组中出现了负数,那么我们还需要考虑乘积中包含负数的情况,显然选择最小的两个负数和最大的一个正数是最优的,即为前两个元素与最后一个元素的乘积。

  3. 上述两个结果中的较大值就是答案。注意我们可以不用判断数组中到底有没有正数,0 或者负数,因为上述两个结果实际上已经包含了所有情况,最大值一定在其中。

public static int maximumProduct(int[] nums) {
    
    
 Arrays.sort(nums);
    int max = Math.max(nums[0] * nums[1] * nums[nums.length - 1],
            nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]);
    return max;
}

方法二:线性扫描

public static int maximumProduct2(int[] nums) {
    
    
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
    int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
    for (int i = 0; i < nums.length; i++) {
    
    
        int n = nums[i];
        if (n > max3) {
    
    
            max1 = max2;
            max2 = max3;
            max3 = n;
        } else if (n <= max3 && n > max2) {
    
    
            max1 = max2;
            max2 = n;
        } else if (n <= max2 && n > max1) {
    
    
            max1 = n;
        }
        if (n < min2) {
    
    
            min1 = min2;
            min2 = n;
        } else if (n < min1 && n >= min2) {
    
    
            min1 = n;
        }
    }
    int max = Math.max(max1 * max2 * max3, min1 * min2 * max3);
    return max;
}

猜你喜欢

转载自blog.csdn.net/m0_46390568/article/details/107718743