版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/83010491
Description
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example
Input: [1,2,3]
Output: 6
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.
Solution
这道题需要注意最大值不一定是最大的三个数相乘,当最小的两个数为负数时,有可能是最小的两个数与最大的一个数相乘,比如:{-2, -5, 1, 2, 3}
,最大值应该为-2 * -5 * 3 = 30
而不是 1 * 2 * 3 = 6
。
public class Solution {
public int maximumProduct(int[] nums) {
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
int max3 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
for(int i = 0; i < nums.length; i++) {
if(nums[i] > max1) {
max3 = max2;
max2 = max1;
max1 = nums[i];
} else if(nums[i] > max2) {
max3 = max2;
max2 = nums[i];
} else if(nums[i] > max3) {
max3 = nums[i];
}
if(nums[i] < min1) {
min2 = min1;
min1 = nums[i];
} else if(nums[i] < min2){
min2 = nums[i];
}
}
return Math.max(max1 * max2 * max3, min1 * min2 * max1);
}
}