题目描述
- LeetCode 628. 三个数的最大乘积
- 给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例1
- 输入: [1,2,3]
- 输出: 6
示例2
- 输入: [1,2,3,4]
- 输出: 24
Java Code
class Solution {
public int maximumProduct(int[] nums) {
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
int min2 = Integer.MAX_VALUE, min1 = Integer.MAX_VALUE;
for (int num : nums) {
if (num >= max1) {
max3 = max2;
max2 = max1;
max1 = num;
} else if (num >= max2) {
max3 = max2;
max2 = num;
} else if (num >= max3) {
max3 = num;
}
if (num <= min1) {
min2 = min1;
min1 = num;
} else if (num <= min2) {
min2 = num;
}
}
return Math.max(max1 * max2 * max3, max1 * min1 * min2);
}
}
参考链接:
原文地址:https://www.cnblogs.com/hglibin/p/10262634.html
时间: 2024-10-09 16:20:04