leetcode-628-Maximum-Product-of-Three-Numbers

描述


Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:

1
2
Input: [1,2,3]
Output: 6

Example 2:

1
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(Java)


1
2
3
4
5
6
7
class Solution {
public int maximumProduct(int[] nums) {
int length = nums.length;
Arrays.sort(nums);
return Math.max(nums[0]*nums[1]*nums[length-1], nums[length-1]*nums[length-2]*nums[length-3]);
}
}

相关问题


(M) Maximum Product Subarray

题目来源