1. 程式人生 > >[Leetcode]628. Maximum Product of Three Numbers

[Leetcode]628. Maximum Product of Three Numbers

hose maximum cnblogs rip max etc 就是 find not


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 class Solution {
2     public int maximumProduct(int[] nums) {
3         Arrays.sort(nums);
4         int p = nums.length;
5         int product1 = nums[p-1]*nums[p-2]*nums[p-3];
6 int product2 = nums[p-1]*nums[0]*nums[1]; 7 return product1>product2?product1:product2; 8 } 9 }

[Leetcode]628. Maximum Product of Three Numbers