博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode]628. Maximum Product of Three Numbers
阅读量:7062 次
发布时间:2019-06-28

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


 

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:

  1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
  2. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

 

思路:乘积最大,则肯定是寻找三个绝对值最大的数相乘。所以先把数组排序,这样数值最大的数为最后三个。第一反应应该会认为

数组末尾三个数乘积就是答案了。但是数组里可能还会有负数,如果数组最开头两个数是负数,且绝对值很大,则答案可能是头两个数

和数组末尾的那个数相乘;

 

1 class Solution {2     public int maximumProduct(int[] nums) {3         Arrays.sort(nums);4         int p = nums.length;5         int product1 = nums[p-1]*nums[p-2]*nums[p-3];6         int product2 = nums[p-1]*nums[0]*nums[1];7         return product1>product2?product1:product2;8     }9 }

 

转载于:https://www.cnblogs.com/David-Lin/p/7740054.html

你可能感兴趣的文章
1849: Cool number
查看>>
【小知识】为什么负数除二和右移一位的结果不一样?
查看>>
ecshop调用指定分类(包含子分类)下所有产品的评论信息
查看>>
树莓派板子中的灯光的信息
查看>>
前端常见的设计模式
查看>>
Java基础——数组Array
查看>>
053(四十五)
查看>>
SQL Server 2008 安全性——透明数据加密(TDE)【转】
查看>>
cmake 增加math.h 标准库
查看>>
Linux下 保存 git账号密码
查看>>
PHP扩展开发--编写一个helloWorld扩展
查看>>
Feature Scaling
查看>>
Java基础班学习笔记(5)
查看>>
PHP 报错:Deprecated: Methods with the same name as their class will not be constructor...
查看>>
自问自答-hadoop自带哪些案例(0.20.2)
查看>>
tachyon 集群安装
查看>>
JS控制元素可见(显示)与不可见(隐藏)
查看>>
特征选择的一点个人笔记
查看>>
移除“xmlns”命名空间
查看>>
CSS九宫格带边框的多种实现
查看>>