【LeetCode】628. 三个数的最大乘积

题目链接:https://leetcode-cn.com/problems/maximum-product-of-three-numbers/

题目描述

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

测试数据

示例 1:

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

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

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

题解

一看到“最大乘积”,第一反应就是先排序,然后最大的三个数乘积就是所求。但是,还要考虑负数的情况,比如[-6,-4,-3,-2,-1,2],这个序列的最大乘积=(-6)*(-4)* 2 = 48。

方法一:先排序,然后返回”最大三个数的乘积“和“最小两个负数及最大数的乘积”,两者的较大者。

时间复杂度:《【LeetCode】628. 三个数的最大乘积》

空间复杂度:《【LeetCode】628. 三个数的最大乘积》

方法二:设置5个变量,分别记录最大的三个数 和 最小的两个数。

时间复杂度:《【LeetCode】628. 三个数的最大乘积》

空间复杂度:《【LeetCode】628. 三个数的最大乘积》

代码

// 方法一

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        return Math.max(nums[0]*nums[1]*nums[n-1], nums[n-1]*nums[n-2]*nums[n-3]);
    }
}
// 方法二

class Solution {
    public int maximumProduct(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 n : nums){
            if (n > max1){
                max3 = max2; max2 = max1; max1 = n; 
            } else if (n > max2){
                max3 = max2; max2 = n;
            } else if (n > max3){
                max3 = n;
            }
            if (n < min1){
                min2 = min1; min1 = n;
            } else if (n < min2){
                min2 = n;
            }
        }
        return Math.max(max1*max2*max3, min1*min2*max1);
    }
}

    原文作者:牧心.
    原文地址: https://blog.csdn.net/Aibiabcheng/article/details/112898042
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞