给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入: [1,2,3]
输出: 6
示例 2:
输入: [1,2,3,4]
输出: 24
注意:
给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-three-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:找出最大的三个数,以及最小的两个数,比较乘积大小。
代码如下:
class Solution {
public int maximumProduct(int[] nums) {
if(nums.length == 3)return nums[0] * nums[1] * nums[2];
int first = Integer.MIN_VALUE,second = Integer.MIN_VALUE,third = Integer.MIN_VALUE;
int first_min = 0,second_min = 0;
for(int i = 0;i < nums.length;i++){
if(nums[i] >= first){
third = second;
second = first;
first = nums[i];
}else if(nums[i] >= second){
third = second;
second = nums[i];
}else if(nums[i] > third)third = nums[i];
if(nums[i] <= first_min){
second_min = first_min;
first_min = nums[i];
}else if(nums[i] <= second_min)second_min = nums[i];
}
int res = first_min * second_min;
return first * second * third > first * res ? first * second * third : first * res;
}
}