628. Maximum Product of Three Numbers

问题:求一个数列里三个数相乘的最大值

Input: [1,2,3]
Output: 6
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.

方针:

最大乘积 =

最大的3个数相乘

or

最小的两个数(两个负数)*最大的数

 

代码参考:

 1 class Solution {
 2 public:
 3     int maximumProduct(vector<int>& nums) {
 4         vector<int> max3v(3, INT_MIN);
 5         vector<int> min2v(2, INT_MAX);
 6         for(int i:nums){
 7             if(i>max3v[0]){
 8                 max3v[2] = max3v[1];
 9                 max3v[1] = max3v[0];
10                 max3v[0] = i;
11             }else if(i>max3v[1]){
12                 max3v[2] = max3v[1];
13                 max3v[1] = i;
14             }else if(i>max3v[2]){
15                 max3v[2] = i;
16             }
17             if(i<min2v[0]){
18                 min2v[1] = min2v[0];
19                 min2v[0] = i;
20             }else if(i<min2v[1]){
21                 min2v[1] = i;
22             }
23         }
24         return max(max3v[0]*max3v[1]*max3v[2],max3v[0]*min2v[0]*min2v[1]);
25     }
26 };

 

posted @ 2020-03-15 12:08  habibah_chang  阅读(128)  评论(0编辑  收藏  举报