您的位置:首页 > 其它

leetcode 628. Maximum Product of Three Numbers 最大的三个元素之积 + 暴力分析

2017-12-21 09:31 337 查看
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:

The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].

Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.

本题题意很简单,首先做排序,其次考虑所有的情况即可

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;

class Solution
{
public:
int maximumProduct(vector<int>& nums)
{
if (nums.size() <= 2)
return 0;
sort(nums.begin(), nums.end());
int n = nums.size();
int res = nums[n - 1] * nums[n - 2] * nums[n - 3];
res = max(res, nums[n - 1] * nums[n - 2] * nums[0]);
res = max(res, nums[n - 1] * nums[0] * nums[1]);
res = max(res, nums[0] * nums[1] * nums[2]);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐