LeetCode 628. Maximum Product of Three Numbers

Given an integer array numsfind 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

Example 3:

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

Constraints:

  • 3 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000

就,求数组里三个数字乘积的最大值。刚开始又给想复杂了,想着如果没有负数或者只有一个负数就是三个最大的正数之积,如果有超过两个负数就是两个最小的负数和最大的正数之积,却忘了还有一种情况是只有两个正数而其他都是负数的情况,应该取两个最小的负数和最大的正数,例子:[-8,-7,-2,10,20]应该是1120。其实这个很简单,直接可以化简为三个最大的正数之积,和两个最小的负数和最大的正数之积,两个里面更大的就是了。

Runtime: 24 ms, faster than 13.05% of Java online submissions for Maximum Product of Three Numbers.

Memory Usage: 55.2 MB, less than 6.95% of Java online submissions for Maximum Product of Three Numbers.

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length;
        int negCount = 0;
        int i = 0;
        while (i < len && nums[i] < 0) {
            negCount++;
            i++;
        }
        if (negCount <= 1) {
            return nums[len - 1] * nums[len - 2] * nums[len - 3];
        } else {
            int negProd = nums[0] * nums[1];
            int posProd = nums[len - 1] * nums[len - 2];
            if (negProd < posProd) {
                return posProd * nums[len - 3];
            } else {
                return negProd * nums[len - 1];
            }
        }
    }
}

还有一种做法是不用sorting,直接for loop一下找出两个最小的数和三个最大的数,同样用上面的方法做比较和判断。就不写了,贴个solutions的代码吧。

public 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 <= min1) {
                min2 = min1;
                min1 = n;
            } else if (n <= min2) {     // n lies between min1 and min2
                min2 = n;
            }
            if (n >= max1) {            // n is greater than max1, max2 and max3
                max3 = max2;
                max2 = max1;
                max1 = n;
            } else if (n >= max2) {     // n lies betweeen max1 and max2
                max3 = max2;
                max2 = n;
            } else if (n >= max3) {     // n lies betwen max2 and max3
                max3 = n;
            }
        }
        return Math.max(min1 * min2 * max1, max1 * max2 * max3);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值