Leetcode628 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,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.

中文大意

給定一個整型數組,找到乘積最大的三個元素,輸出爲最後的乘積。


分析

(1)注意數組中元素值的範圍爲:正數、0、負數,要是最後的乘積的值最大,那麼負元素的個數爲兩個或零個。

(2)同時我們要注意三個乘積結果的位數,是否會導致溢出,由於這道題目中元素絕對值的最大值爲1000,而整型是32位的,所以是不會溢出的。

(3)爲了獲得最後的乘積最大,那麼我們需要獲得絕對值大的幾個元素。


java代碼實現一

爲了方便獲得元素中的幾個最大值和幾個最小值,所以可以先對數組排序。

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);//調用Arrays.sort()是直接在原數組上排序的。
        int  mulfont = nums[0] * nums [1];
        int  mulend = nums[nums.length -2] * nums[nums.length-3];
        if(mulfont <= mulend){
            return mulend * nums[nums.length -1];
        }
        return mulfont * nums[nums.length -1];       
    }
}

java代碼實現二

通過遍歷數組,然後得到三個比較大的元素和兩個比較小的元素。

class Solution {
    public int maximumProduct(int[] nums) {
        int max1 = Integer.MIN_VALUE,max2 = Integer.MIN_VALUE,max3 = Integer.MIN_VALUE,min1 = Integer.MAX_VALUE,min2 = Integer.MAX_VALUE;
        
        for(int ele :nums){
            if(ele > max1){
                max3 = max2;
                max2 = max1;
                max1 = ele;
            }else if(ele >max2){
                max3 = max2;
                max2 = ele;
            }else if(ele > max3){
                max3 = ele;
            }
            
            if(ele < min1){
                min2 = min1;
                min1 = ele;
            }else if(ele < min2){
                min2 = ele;
            }
        }
        
        return Math.max(max1 * max2 * max3 , max1 * min1 * min2);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章