Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Idea: In order to find the largest product, we need to traverse the array while maintain ing three numbers that can multiply the largest number. So, really, only three maintians can do it? Since there may be negative numbers in the array, what we really need for maintian is five numbers, max, mid, min, smallest 1, smallest 2, and then the final maximum product will be max*mid*min and Max * smallest 1 * smallest 2. So, to understand this, we just need to discuss the classification of new elements in the process of traversal. The code is as follows:
public int maximumProduct(int[] nums) {
//special case
if (nums == null || nums.length < 3) return 0;
if (nums.length == 3) return nums[0] * nums[1] * nums[2];
//base case
int[] base = new int[3];
for (int i = 0; i < 3; i++) {
base[i] = nums[i];
}
Arrays.sort(base);
//general case
//Notice here that s1 and s2 are initialized to two minimum values at the beginning, because perhaps the two numbers that appear at the beginning are always the two minimum negative numbers in the whole array.
int min = base[0], mid = base[1], max = base[2], s1 = base[0], s2 = base[1];
for (int i = 3; i < nums.length; i++) {
int num = nums[i];
if (num > max) {
min = mid;
mid = max;
max = num;
} else if (num > mid) {
min = mid;
mid = num;
} else if (num > min) {
min = num;
} else if (num < s1) {
s2 = s1;
s1 = num;
} else if (num < s2) {
s2 = num;
} else {
continue;
}
}
return Math.max(max * mid * min, max * s1 * s2);
}