###### tags: `Leetcode` `easy` `math` `sort` `python` `c++`
# 628. Maximum Product of Three Numbers
## [題目連結:] https://leetcode.com/problems/maximum-product-of-three-numbers/
## 題目:
Given an integer array ```nums```, find three numbers whose product is maximum and return the maximum product.
**Example 1:**
```
Input: nums = [1,2,3]
Output: 6
```
**Example 2:**
```
Input: nums = [1,2,3,4]
Output: 24
```
**Example 3:**
```
Input: nums = [-1,-2,-3]
Output: -6
```
## 解題想法:
* 題目要求數組中任意三個數的最大乘積
* 先將數組排序:
* case1:數組可能有正有負
* 最大可以是, **左邊兩個最負的相乘,搭配最右邊的**
* case2: 若數組全正or全負
* 最大的乘積為, **最右邊三個相乘**
## Python:
``` python=
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
max1=nums[0]*nums[1]*nums[-1]
max2=nums[-1]*nums[-2]*nums[-3]
return max(max1,max2)
if __name__ == '__main__':
result=Solution()
ans=result.maximumProduct(nums = [1,2,3])
print(ans) #6
```
## C++:
``` cpp=
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int maximumProduct(vector<int>& nums) {
//<algorithm> for sort()
int n=nums.size();
sort(nums.begin(),nums.end());
int max1=nums[0]*nums[1]*nums[n-1];
int max2=nums[n-1]*nums[n-2]*nums[n-3];
return max(max1,max2);
}
};
int main(){
Solution res;
vector<int> nums={1,2,3,4};
int ans=res.maximumProduct(nums);
cout<<ans<<endl;
return 0;
}
```