给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
- 示例 1:
输入: [1,2,3]
输出: 6
- 示例 2:
输入: [1,2,3,4]
输出: 24
- 注意:
给定的整型数组长度范围是[3,104]
,数组中所有的元素范围是[-1000, 1000]
。
输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
- 先排序
class Solution {
public:
void quickSort(vector<int>& nums, int low, int high) {
if (high <= low) {
return;
}
int key = nums[low];
int i = low;
int j = high+1;
while(true) {
while(nums[++i] < key) {
if (i == high) {
break;
}
}
while(nums[--j] > key) {
if (j == low) {
break;
}
}
if (i >=j ) {
break;
}
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
nums[low] = nums[j];
nums[j] = key;
quickSort(nums, low, j-1);
quickSort(nums, j+1, high);
}
int maximumProduct(vector<int>& nums) {
quickSort(nums, 0, nums.size()-1);
return max(nums[nums.size()-1] * nums[nums.size()-2] * nums[nums.size()-3], nums[nums.size()-1] * nums[0] * nums[1]);
}
};
- 线性扫描
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int min1 = INT_MAX, min2 = INT_MAX;
int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;
for (const auto& num: nums) {
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2) {
min2 = num;
}
if (num > max1) {
max3 = max2;
max2 = max1;
max1 = num;
} else if (num > max2) {
max3 = max2;
max2 = num;
} else if (num > max3){
max3 = num;
}
}
return max(max1 * max2 * max3, max1 * min1 * min2);
}
};
来源:力扣(LeetCode)