628. Maximum Product of Three Numbers
Posted habibah-chang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };
以上是关于628. Maximum Product of Three Numbers的主要内容,如果未能解决你的问题,请参考以下文章
628. Maximum Product of Three Numbers
628. Maximum Product of Three Numbers
628. Maximum Product of Three Numbers
Leetcode_easy628. Maximum Product of Three Numbers