LeetCode Maximum Product of Three Numbers

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

 

Note:

  1. The length of the given array will be in range [3,10^ 4] and all elements are in the range [-1000, 1000].
  2. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

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

示例 1:

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

示例 2:

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

注意:

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

题解:给定一个数组,求其中的任意三个元素乘积构成的最大的数。拿到这道题,lz就想到先对这个数组进行从小到大排序,然后再挑选。但是仔细一想,有一种非常简单的方式,因为已经对该数组从小到大排序了,那么不出意外,该最大的三个数只可能出现在该数组的前3个数;最后的3个数;或者是前两个数,和最后一个数;或者是前一个数,后两个数。因为有可能该数组中的元素存在负数,那么有可能前几个数相乘有可能会最大;但是最终都不会逃过上述这四种情况。

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

代码非常简单,但是理解却非常难!深入理解后,就能做出最简单的解法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值