LeetCode Maximum Product of Three Number s(java)

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

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

Example 2:
Input: [1,2,3,4]
Output: 24
思路:为了找找到最大的乘积,我们需要在遍历数组的同时maintain三个可能乘出最大数的数字,那么真的只要maintian三个就可以吗?由于数组中可能会出现负数,因此我们真正需要maintian的是5个数字,max, mid, min, smallest1, smallest2, 然后最后的最大乘积会在max*mid*min和max*smallest1*smallest2中选取最大值,因此,搞清楚了这个,我们只需要在遍历的过程中对于新来的元素分类讨论即可。代码如下:
public int maximumProduct(int[] nums) {
        //special case
        if (nums == null || nums.length < 3) return 0;
        if (nums.length == 3) return nums[0] * nums[1] * nums[2];
        //base case
        int[] base = new int[3];
        for (int i = 0; i < 3; i++) {
            base[i] = nums[i];
        }
        Arrays.sort(base);
        //general case
        //注意这里s1和s2的初始化为一开始的两个最小值,因为也许一开始出现的两个数就一直是整个数组里的最小的两个负数。
        int min = base[0], mid = base[1], max = base[2], s1 = base[0], s2 = base[1];
        for (int i = 3; i < nums.length; i++) {
            int num = nums[i];
            if (num > max) {
                min = mid;
                mid = max;
                max = num;
            } else if (num > mid) {
                min = mid;
                mid = num;
            } else if (num > min) {
                min = num;
            } else if (num < s1) {
                s2 = s1;
                s1 = num;
            } else if (num < s2) {
                s2 = num;
            } else {
                continue;
            }
        }
        return Math.max(max * mid * min, max * s1 * s2);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值