领扣LintCode算法问题答案-1119. 三个数的最大乘积
发布日期:2021-06-30 17:09:54 浏览次数:2 分类:技术文章

本文共 1863 字,大约阅读时间需要 6 分钟。

领扣LintCode算法问题答案-1119. 三个数的最大乘积

目录

1119. 三个数的最大乘积

描述

给定一个整数数组,找到三个元素,使乘积最大,返回该积。

  1. 数组的长度范围为[3, 10^4],所有的元素范围为[-1000, 1000]。
  2. 任意三个元素的积不会超过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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1126. 合并两棵二叉树
下一篇:【精】领扣LintCode算法问题答案:1115. 二叉树每层的平均数

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月13日 03时32分40秒