Leetcode Add to List 628. Maximum Product of Three Numbers
来源:互联网 发布:关于网络的论文 编辑:程序博客网 时间:2024/06/03 20:51
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.
思路:刚开始想的有点复杂,其实这道题就是判定最大的三个相乘和最小的两个(在均为负数)和最大的数相乘的最大值
一下是AC代码
class Solution {
public:
int maximumProduct(vector<int>& nums) {
//1.
if(nums.size() < 3)
return 0;
//2. 对数组进行排序
sort(nums.begin(),nums.end());
int n = nums.size() - 1;
int max_s = nums[n] * nums[n-1] * nums[n-2];
max_s = max(max_s,nums[n] * nums[1] * nums[0]);
return max_s;
}
};
public:
int maximumProduct(vector<int>& nums) {
//1.
if(nums.size() < 3)
return 0;
//2. 对数组进行排序
sort(nums.begin(),nums.end());
int n = nums.size() - 1;
int max_s = nums[n] * nums[n-1] * nums[n-2];
max_s = max(max_s,nums[n] * nums[1] * nums[0]);
return max_s;
}
};
阅读全文
0 0
- Leetcode Add to List 628. Maximum Product of Three Numbers
- [leetcode]628. Maximum Product of Three Numbers
- leetcode#628. Maximum Product of Three Numbers
- leetcode: 628. Maximum Product of Three Numbers
- leetcode 628. Maximum Product of Three Numbers
- [LeetCode] 628. Maximum Product of Three Numbers
- [leetcode]628. Maximum Product of Three Numbers
- LeetCode 628. Maximum Product of Three Numbers
- leetcode -- 628. Maximum Product of Three Numbers
- [LeetCode]628. Maximum Product of Three Numbers
- [LeetCode]628. Maximum Product of Three Numbers
- 【LeetCode】628. Maximum Product of Three Numbers
- LeetCode 628. Maximum Product of Three Numbers
- Leetcode:628. Maximum Product of Three Numbers
- LeetCode 628. Maximum Product of Three Numbers
- 【LeetCode】628. Maximum Product of Three Numbers
- LeetCode-628. Maximum Product of Three Numbers
- leetcode 628. Maximum Product of Three Numbers
- #bzoj3394#雪后村庄(启发式合并 + 哈希)
- 2105. 【NOIP2016普及组复赛】魔法阵
- Mongodb浅解
- dump
- XML STUDY_NOTE
- Leetcode Add to List 628. Maximum Product of Three Numbers
- 【数据结构】揭开面纱(摘抄)
- 一个c程序
- 四.c++中的算法--排序及相关操作---堆操作
- Python 面向对象(进阶篇)
- Socket编程之htons(), ntohl(), ntohs(),htons() 函数
- 1.DeckBulid 基本代码笔记
- 不用管这个QwQ
- 四.c++中的算法--排序及相关操作---合并排序