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.
本题题意很简单,首先做排序,其次考虑所有的情况即可
代码如下:
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; } };
相关文章推荐
- 每天一道LeetCode----从数组中选择若干不连续元素使得总和最大
- LeetCode-643:Maximum Average Subarray I (k个元素的最大子数组)
- [LeetCode] 689. Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
- 给定整型数组,其中每个元素表示木板的高度,木板的宽度都相同,求这些木板拼出的最大矩形的面积。并分析时间复杂度。
- 实验九指针1、程序填空:下列程序在数组中同时查找最大元素和最小元素的下标,分别存放在 main()函数的max 和 min 变量中。要求:根据运行结果分析程序和填空,并注释说明填充依据。
- leetcode 05 最长相同元素之间的的最大字符串 && 06 Z形字符串排序
- 给定整型数组,其中每个元素表示木板的高度,木板的宽度都相同,求这些木板拼出的最大矩形的面积。并分析时间复杂度。
- 实验9 指针1 、程序填空:下列程序在数组中同时查找最大元素和最小元素的下标,分别存放在 main()函数的max 和 min 变量中。要求:根据运行结果分析程序和填空,并注释说明填充依
- Leetcode740. 删除元素获取最大值
- 数据结构习题分析:已知由一个线性链表表示的线性表中含有三类字符的数据元素,是编写算法将该线性表分割为三个循环链表,其中每个。。。。。
- leetcode 565. Array Nesting 最大的环的元素数量
- 每天一道LeetCode-----在给定数组中找到一个子数组,使得这个子数组的元素乘积最大
- leetcode 99. Recover Binary Search Tree BST二叉搜索树的两元素交换的恢复 + 中序遍历 + 很棒的分析和做法
- LeetCode Container With Most Water 查找容水量最大的容器 动态规划法思想分析
- Leetcode421. 找出数组中两个元素异或的最大值
- LeetCode (20) house robber (数组不相邻元素最大值)
- LeetCode 16. 3Sum Closest--寻找数组中的三个元素和,该和与给定的值的差最小,输出这个和(三个元素可以不连续)
- LeetCode 628. Maximum Product of Three Numbers (最大三数乘积)
- LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
- leetcode-java.T015_3Sum---给定一个n个元素的数组,是否存在a,b,c三个元素,使用得a+b+c=0,找出所有符合这个条件的三元组