【Leetcode】628. Maximum Product of Three Numbers(Easy)

1.題目

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.

2.思路

先把整數序列進行由小到大的排序。序列中有正有負,三個數的乘積。想要最大,一定有排序後的隊列中的最後一個數字。另外兩個,要麼是前頭的兩個數(可能是兩個負數,相乘得正數),要麼是最後一個數字前面的兩個數。

3.算法

class Solution {
    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int len=nums.length;
        
        int temp1,temp2;
        temp1=nums[0]*nums[1];
        temp2=nums[len-2]*nums[len-3];
        
        return nums[len-1]*(temp1>=temp2?temp1:temp2);
    }
}

4.總結

開始寫的時候,忘記了負數的情況。還是要仔細一點。

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