leetcode 628. Maximum Product of Three Numbers(三个数的最大乘积)

Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

Example 1:

Input: nums = [1,2,3]
Output: 6
Example 2:

Input: nums = [1,2,3,4]
Output: 24

给出一个数组,找出其中3个数,使乘积最大

思路:
假如有两个数,乘积最大的是两个最大正数的积或者两个最小负数的积
那么3个数的情况下,最大乘积的即为最大的数 与 其余两个数的最大乘积 的积

这时需要找出数组中最大的数 和 其余两个最大的数和最小的数
可对数组排序,或者直接找到最大的三个数和最小的两个数

这里用排序

    public int maximumProduct(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        Arrays.sort(nums);
        int n = nums.length;
        
        int max1 = nums[0] * nums[1] * nums[n-1];
        int max2 = nums[n-3] * nums[n-2] * nums[n-1];
        
        return Math.max(max1, max2);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值