LeetCode 628. Maximum Product of Three Numbers

来源:互联网 发布:2016淘宝开店教程 编辑:程序博客网 时间:2024/05/20 13:08

LeetCode 628. Maximum Product of Three Numbers

Description:

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


分析:

这道题很简单,先按从小到大排序,考虑后三个数的乘积、前两个数(负数)和最后一个数的乘积,这两个乘积孰大孰小即可。
代码如下:

class Solution {public:    int maximumProduct(vector<int>& nums) {        sort(nums.begin(), nums.end());        int size = nums.size();        int temp1 = nums[size - 1] * nums[size - 2] * nums[size - 3];        int temp2 = nums[0] * nums[1] * nums[size - 1];        return temp1 > temp2 ? temp1 : temp2;    }};
原创粉丝点击