给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入: [1,2,3] 输出: 6
示例 2:
输入: [1,2,3,4] 输出: 24
注意:
- 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
- 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
https://leetcode-cn.com/problems/maximum-product-of-three-numbers/description/
class Solution {
public int maximumProduct(int[] nums) {
//初始化最大的3个数
int[] max = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
//初始化2个最小的数,因为要求为负数所以默认值0即可
int[] min = new int[2];
//max数组中最小的数的下标
int minIndexOfMax = 0;
//min数组中最大的数的下标
int maxIndexOfMin = 0;
for (int num : nums) {
//当num大于max中最小的数时,将其替换,并更改下标
if (num > max[minIndexOfMax]) {
max[minIndexOfMax] = num;
minIndexOfMax = getMinIndex(max);
}
//当num小于min中最大的数时,将其替换,并更改下标
if (num < min[maxIndexOfMin]) {
min[maxIndexOfMin] = num;
maxIndexOfMin = min[0] > min[1] ? 0 : 1;
}
}
//3个最大值的积
int res = max[0] * max[1] * max[2];
//当存在两个负数时,最大值可能更改
if (min[maxIndexOfMin] < 0) {
//两个负数乘以最大值
int temp = min[0] * min[1] * Math.max(Math.max(max[0], max[1]), max[2]);
res = Math.max(res, temp);
}
return res;
}
/** 取数组中最小值的下标 */
private int getMinIndex(int[] max) {
if (max[0] < max[1]) {
return max[0] < max[2] ? 0 : 2;
}
return max[1] < max[2] ? 1 : 2;
}
}