628. Maximum Product of three Numbers
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [Output:6]
Example 2:
Input: [1,2,3,4]
output:24
Note:
The length of the given array would be a range [3,104] and all elements is in the range [-1000, 1000]. Multiplication of any three numbers in the input won ' t exceed the range of 32-bit signed integer.
Given an array, the maximum product of the array of three arrays is obtained.
At first, I didn't think about that much, so I think the product of the last three numbers should be the largest after sorting. But there are still negative numbers.
After considering negative numbers, on the basis of the original idea, think about:
Since it is the product of three numbers, it is sure to take the largest one, and then the second largest, the third largest number product compared to the first small, the second small product comparison, take larger on it.
Specifically how to take out these several numbers:
1. Quick Sort After (O (NLOGN))
2. Remove (O (n)) while traversing the process
Solution One:
Class Solution {public
int maximumproduct (int[] nums) {
arrays.sort (nums);
int length = Nums.length;
if (Nums[0]*nums[1] < nums[length-3]*nums[length-2])
return nums[length-1]*nums[length-2]*nums[length-3];
else return nums[length-1]*nums[0]*nums[1];
}
}
Solution Two:
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) {
min2 = min1;
Min1 = n;
} else if (n < min2) {
min2 = n;
}
if (n > Max1) {
max3 = max2;
Max2 = max1;
MAX1 = n;
} else if (n > Max2) {
max3 = max2;
MAX2 = n;
} else if (n > Max3) {
max3 = n;
}
}
Return Math.max (MIN1*MIN2*MAX1,MAX1*MAX2*MAX3);
}
}