当前位置:网站首页>LeetCode_628_三个数的最大乘积
LeetCode_628_三个数的最大乘积
2022-08-10 10:43:00 【Fitz1318】
题目链接
题目描述
给你一个整型数组 nums
,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入:nums = [1,2,3]
输出:6
示例 2:
输入:nums = [1,2,3,4]
输出:24
示例 3:
输入:nums = [-1,-2,-3]
输出:-6
提示:
3 <= nums.length <= 10^4
-1000 <= nums[i] <= 1000
解题思路
对数组的构成进行分情况讨论
- 如果全是正数:
- 选择最大的三个正数,即最大的三个数
- 如果至少两个正数,只有一个负数:
- 至少有三个正数:选择最大的三个正数,即最大的三个数
- 只有两个正数:只有三个数可以选择,即最大的三个数
- 如果至少一个正数,只有两个负数:
- 至少有三个正数:选择最大的三个正数,即最大的三个数,或者是选择两个负数和最大的一个正数,即最小的两个数和最大的一个数
- 只有两个正数:选择两个负数和最大的一个正数,即最小的两个数和最大的一个数
- 只有一个正数:只有三个数可以选择,即最大的三个数
- 如果全是负数:
- 选择最大的三个负数,即最大的三个数
综上所述,结果为最大的三个数和最小的两个数和最大的一个数中的更大值
AC代码
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int len = nums.length;
int ans = 0;
ans = Math.max(nums[len - 1] * nums[len - 2] * nums[len - 3], nums[len - 1] * nums[0] * nums[1]);
return ans;
}
}
边栏推荐
- 3 injured in 'electrical accident' at Google data center
- STM32封装ESP8266一键配置函数:实现实现AP模式和STA模式切换、服务器与客户端创建
- Kyligence 通过 SOC 2 Type II 审计,以可信赖的企业级产品服务全球客户
- MongoDB database notes
- What is affecting MySQL performance?
- 金九银十跳槽旺季:阿里、百度、京东、美团等技术面试题及答案
- Dry goods!ASSANet: Making PointNet++ faster and stronger
- Double.doubleToLongBits()方法使用
- Break through the dimensional barriers and let the dolls around you move on the screen!
- 【无标题】
猜你喜欢
GPU accelerated Pinterest recommendation model, the number of parameters increased by 100 times, and the user activity increased by 16%
8月份DB-Engines 数据库排行榜最新战况
Research on motion capture system for indoor combined positioning technology
【勇敢饭饭,不怕刷题之链表】链表反转的几种情况
干货!ASSANet:让PointNet++更快更强
Gold, nine, silver and ten job-hopping seasons: technical interview questions and answers on Alibaba, Baidu, JD.com, and Meituan
Introduction to cross-end development of Taro applet
GPU加速Pinterest推荐模型,参数量增加100倍,用户活跃度提高16%
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security
随机推荐
Break through the dimensional barriers and let the dolls around you move on the screen!
blocking non-blocking poll mechanism asynchronous
3 injured in 'electrical accident' at Google data center
从产品角度看 L2 应用:为什么说这是一个游乐场?
HCIP ---- VLAN
内存问题难定位,那是因为你没用ASAN
Dry goods!ASSANet: Making PointNet++ faster and stronger
关于json转换器缺失的问题,报错内容:No converter found for return value of type
一文带你搞懂中断按键驱动程序之poll机制
【勇敢饭饭,不怕刷题之链表】链表中有环的问题
Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security
Cybersecurity Notes 5 - Digital Signatures
Store limited time seckill function system
干货!ASSANet:让PointNet++更快更强
阻塞 非阻塞 poll机制 异步
【无标题】
what is rtems
CodeChef STMRRG String Merging (dp)
"Scalability" extensibility best practices: lessons from eBay
越折腾越好用的 3 款开源 APP