The biggest product of three numbers
November 24, 2024Less than 1 minute
The biggest product of three numbers
The product cannot go beyond the int_MAX
public static int sort (int[] nums){
Arrays.sort(nums); // O(n log n)
int n = nums.length;
return Math.max(nums[0] * nums[1] * nums[n-1], nums[n-1] * nums[n-2] * nums[n-3]);
}
public class Solution {
public static int sort(int[] nums) {
// 初始化最小值和最大值
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
// 遍历数组,更新最大最小值
for (int x : nums) {
// 更新最小值
if (x < min1) {
min2 = min1;
min1 = x;
} else if (x < min2) {
min2 = x;
}
// 更新最大值
if (x > max1) {
max3 = max2;
max2 = max1;
max1 = x;
} else if (x > max2) {
max3 = max2;
max2 = x;
} else if (x > max3) {
max3 = x;
}
}
// 返回最大乘积
return Math.max(min1 * min2 * max1, max1 * max2 * max3);
}
}