LeetCode 628 Maximum Product of Three Numbers

来源:互联网 发布:宁夏干部网络培训 编辑:程序博客网 时间:2024/06/05 13:30

题目:

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:

  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,104],并且元素的范围是 [-1000, 1000] ,且乘积不会超int。

最大值有两种可能:

  1. 负数 * 负数 * 正数
  2. 正数 * 正数 * 正数
因为数组长度一定大于3,所以直接写返回函数即可。
代码:
class Solution {public:    int maximumProduct(vector<int>& nums) {        sort(nums.begin(), nums.end());        return max(nums[0]*nums[1]*nums[nums.size()-1], nums[nums.size()-3]*nums[nums.size()-2]*nums[nums.size()-1]);    }};



原创粉丝点击