給定一個整型數組,在數組中找出由三個數組成的最大乘積,並輸出這個乘積。
示例 1:
輸入: [1,2,3]
輸出: 6
示例 2:
輸入: [1,2,3,4]
輸出: 24
注意:
給定的整型數組長度範圍是[3,104],數組中所有的元素範圍是[-1000, 1000]。
輸入的數組中任意三個數的乘積不會超出32位有符號整數的範圍。
題解:
由於題目中已經限定了數組的長度範圍,所以不必考慮小於三的情況。
兩種思路:
- 思路1:排序,比較最後三個的乘積和最後一個乘上前兩個,取最大值
- 思路2:從前往後找,最小的兩個和最大的三個,同樣,比較最大的三個和最小的兩個乘上最大的那個。
思路1:
時間和內存消耗爲:
代碼爲:
class Solution {
public int maximumProduct(int[] nums) {
//負數情況
//只用考慮前兩個數
int n=nums.length;
Arrays.sort(nums);
return Math.max(nums[n-1]*nums[n-2]*nums[n-3],nums[0]*nums[1]*nums[n-1]);
}
}
思路2:
時間和內存消耗爲:
代碼爲:
class Solution {
public int maximumProduct(int[] nums) {
int min1=Integer.MAX_VALUE;
int min2=Integer.MAX_VALUE;
int max1=Integer.MIN_VALUE;
int max2=Integer.MIN_VALUE;
int max3=Integer.MIN_VALUE;
for(int num:nums){
if(num<=min2){
if(num<=min1){
min2=min1;
min1=num;
}else{
min2=num;
}
}
if(num>=max3){
if(num>=max2){
if(num>=max1){
max3=max2;
max2=max1;
max1=num;
}else{
max3=max2;
max2=num;
}
}else{
max3=num;
}
}
}
return Math.max(max1*max2*max3,min1*min2*max1);
}
}