MaximumProductofThreeNumbers

来源:互联网 发布:网络机柜的作用 编辑:程序博客网 时间:2024/05/22 02:12

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,104] 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.

思路

题目是要求一个数组中任意三个数的最大乘积,但是并不是要找出三个最大的数这么简单的。因为数组

中是可能存在负数的,会出现两负一正乘积仍然为正的情况。比较出max1*max2*max3与min1*min2*max1中较大

的数返回即可。


    public int maximumProduct(int[] nums) {        int max1 = Integer.MIN_VALUE;        int max2 = Integer.MIN_VALUE;        int max3 = Integer.MIN_VALUE;        int min1 = Integer.MAX_VALUE;        int min2 = Integer.MAX_VALUE;        for(int i=0; i<nums.length; i++) {        if(nums[i] > max1) {        max3 = max2; max2 = max1; max1 = nums[i];          } else if(nums[i] > max2) {        max3 = max2; max2 = nums[i];         } else if(nums[i] > max3) {        max3 = nums[i];        }                if(nums[i] < min1) {        min2 = min1; min1 = nums[i];        } else if(nums[i] < min2) {        min2 = nums[i];        }        }        if(max2*max3 > min1*min2) {        return max2*max3*max1;        }         return min1*min2*max1;    }