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

xiaoxiao2021-02-28  4

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; } };
转载请注明原文地址: https://www.6miu.com/read-2050152.html

最新回复(0)