LeetCode628 Maximum Product of Three Numbers
Given an integer array, find three numbers whose product is maximum and output the maximum product.
this problem is easy and have nothing to do with the subarray related problem.
class Solution {
public int maximumProduct(int[] nums) {
if (nums.length < 3) return -1;
Arrays.sort(nums);
//we have two subcases: it's either the least two and the biggest one that's mulilication is max, or the max threes muplication is the biggest
return Math.max(nums[0]*nums[1]*nums[nums.length-1], nums[nums.length-3] * nums[nums.length-2] * nums[nums.length-1]);
}
}
the previous code is my writing, first I thought it was pretty low, but it looks exactly one of the solutions!
and can we solve this problem in O(n)? yes we can.
it actually is an optimal of previous solution. see, we don;t need to presort the array to find the (min1,min2,max1) or (max1, max2, max3), we just needs to iterate once to get the topk or min_k if K is a constant number.
public class Solution {
public int maximumProduct(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 n: nums) {
if (n <= min1) {v//we needs to update min1 and min2
min2 = min1;
min1 = n;
} else if (n <= min2) { // n lies between min1 and min2, then we needs to maintain min2
min2 = n;
}
if (n >= max1) { // n is greater than max1, max2 and max3, then we need to update max1 max 2 and max3
max3 = max2;
max2 = max1;
max1 = n;
} else if (n >= max2) { // n lies betweeen max1 and max2, then we only needs to update max2 and max3
max3 = max2;
max2 = n;
} else if (n >= max3) { // n lies betwen max2 and max3, then we only needs to update max3
max3 = n;
}
}
return Math.max(min1 * min2 * max1, max1 * max2 * max3);
}
}

浙公网安备 33010602011771号