LeetCode——Maximum Product of Three Numbers
2024-09-24 13:25:40
Question
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.
Solution
排序,要么最大的三个正数乘积最大,要么是两个最小的负数和最大的正数乘积最大。
Code
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end(), comp);
return max(nums[0] * nums[1] * nums[2], nums[0] * nums[nums.size() - 1] * nums[nums.size() - 2]);
}
static bool comp(int& a, int& b) {
return a > b;
}
};
最新文章
- 如何让老Mac机支持USB安装Windows
- 20151011 C# 第一篇 运算符
- viojs1908无线网路发射器选址
- angularJS之事件处理
- gif修改背景透明
- html背景图片拉伸至全屏
- dojo中的xhrPost请求(JSON)
- IQueryable &; IEnumberable 区别
- 饮冰三年-人工智能-linux-03 Linux文件管理(权限管理+归档+压缩)
- 两个时间点计算相隔几年,几个月,几天-java
- PyTorch(二)Intermediate
- springcloud 入门 11 (Hystrix Dashboard)
- JavaScript 上万条数据 导出Excel文件(改装版)
- MySQL Execution Plan--数据排序操作
- Oracle下PLSQL连接没有数据库的问题
- [SimpleOJ229]隧道
- ZOJ 3964 NIM变形
- Python的subprocess模块(一)
- sklearn 中模型保存的两种方法
- 小程序swiper配置参数使用