领扣LintCode算法问题答案-1119. 三个数的最大乘积
发布日期:2021-06-30 17:09:54
浏览次数:2
分类:技术文章
本文共 1863 字,大约阅读时间需要 6 分钟。
领扣LintCode算法问题答案-1119. 三个数的最大乘积
目录
1119. 三个数的最大乘积
描述
给定一个整数数组,找到三个元素,使乘积最大,返回该积。
- 数组的长度范围为[3, 10^4],所有的元素范围为[-1000, 1000]。
- 任意三个元素的积不会超过32位有符号整数的范围。
样例 1:
输入: [1,2,3]输出: 6
样例 2:
输入: [1,2,3,4]输出: 24
题解
public class Solution { /** * @param nums: an integer array * @return: the maximum product */ public int maximumProduct(int[] nums) { // Write your code here if (nums.length == 3) { return nums[0] * nums[1] * nums[2]; } Arrays.sort(nums); int positiveCount = 0; int negativeCount = 0; for (int num : nums) { if (num > 0) { break; } else { negativeCount++; } } positiveCount = nums.length - negativeCount; if (positiveCount >= 1 && negativeCount >= 2) { int maxPositive = nums[nums.length - 2] * nums[nums.length - 3]; int maxNegative = nums[0] * nums[1]; return nums[nums.length - 1] * Math.max(maxPositive, maxNegative); } else if (positiveCount >= 3) { return nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]; } else { int positiveIndex = 0; int negativeIndex = 0; int totalValue = 1; for (int i = 0; i < 3; i++) { if (nums[negativeCount + positiveIndex] < Math.abs(nums[nums.length - positiveCount - negativeIndex])) { totalValue *= nums[negativeCount + positiveIndex]; positiveIndex++; } else { totalValue *= nums[nums.length - positiveCount - negativeIndex]; negativeIndex++; } } return totalValue; } }}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
转载地址:https://le-yi.blog.csdn.net/article/details/108841695 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月13日 03时32分40秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
软件质量的8个特性
2019-04-30
应届渣渣前端的艰难求职之路
2019-04-30
2021年不可错过的17种JS优化技巧(一)
2019-04-30
月薪15~20k的前端面试问什么?
2019-04-30
在 Vue 中用 Axios 异步请求API
2019-04-30
mysql——介绍及安装与基本用法
2019-04-30
MySQL数据库之索引
2019-04-30
MYSQL——事务操作+视图+存储引擎
2019-04-30
Mysql——完全备份+增量备份+备份恢复
2019-04-30
MySQL进阶查询(SELECT 语句高级用法)
2019-04-30
Mysql 之主从复制
2019-04-30
LVS负载均衡------NAT模式
2019-04-30
squid代理-----透明代理模式
2019-04-30
squid代理介绍----ACL控制应用+sarg日志分析+反向代理
2019-04-30
redis集群之主从模式+哨兵模式
2019-04-30
JavaScript原生开关灯效果
2019-04-30
企业邮箱如何申请注册,邮箱申请如何免费注册?
2019-04-30
微信企业邮箱,手机邮箱格式地址怎么写?
2019-04-30