628. Maximum Product of Three Numbers数组中三个数乘积最大
2017-12-12 16:06
253 查看
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Example 2:
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.
题目解释:数组中任意三个数乘积,找到这个乘积的最大值。需要考虑的是数组中可能含有负数,所以解题思路就是将数组进行升序排序,然后如果数组有负数,即在前几个元素处,故只需要比较前两个数的成绩和倒数二和倒数第三个数的乘积的大小即可。
class Solution {
public int maximumProduct(int[] nums) {
if(nums==null||nums.length<=2)return 0;
Arrays.sort(nums);
int n=nums.length;
if(nums[0]*nums[1]<nums[n-2]*nums[n-3]){
return nums[n-1]*nums[n-2]*nums[n-3];
}else return nums[0]*nums[1]*nums[n-1];
}
}
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.
题目解释:数组中任意三个数乘积,找到这个乘积的最大值。需要考虑的是数组中可能含有负数,所以解题思路就是将数组进行升序排序,然后如果数组有负数,即在前几个元素处,故只需要比较前两个数的成绩和倒数二和倒数第三个数的乘积的大小即可。
class Solution {
public int maximumProduct(int[] nums) {
if(nums==null||nums.length<=2)return 0;
Arrays.sort(nums);
int n=nums.length;
if(nums[0]*nums[1]<nums[n-2]*nums[n-3]){
return nums[n-1]*nums[n-2]*nums[n-3];
}else return nums[0]*nums[1]*nums[n-1];
}
}
相关文章推荐
- 无序数组中,三个数的乘积最大
- 拼多多笔试题一:给出一个无序整数数组,求任意三个数的最大乘积
- 求无序数组中的三个数的最大乘积
- 笔试题 找到数组中,三个数乘积最大的结果
- 拼多多内推笔试一:求数组中任意三个数的最大乘积
- 编程之美2.13 子数组的最大乘积
- [编程之美]子数组的最大乘积
- 子数组最大乘积
- 求子数组的最大乘积
- 子数组的最大乘积
- 2.13 子数组的最大乘积
- 最大连续子数组和、乘积(动态规划)
- 子数组的最大乘积
- 【开放 5月18日 发布】:子数组的最大乘积问题_____问题简单,请思考如何逐步降低时间复杂度,跟帖回复,群内讨论.
- 求数组中n-1个元素的乘积的最大值(某公司2007年校园招聘笔试试题)
- [算法]数组子数组的最大累乘积
- 【编程之美】2.13 子数组的最大乘积
- 【面试题】连续子数组乘积最大值与柱状图中找最大矩形
- JAVA代码—算法基础:最大连续子数组乘积问题
- 子数组的最大乘积