方法一:排序
我們將數組進行升序排序,如果數組中所有的元素都是非負數,那么答案即為最后三個元素的乘積。
如果數組中出現了負數,那么我們還需要考慮乘積中包含負數的情況,顯然選擇最小的兩個負數和最大的一個正數是最優的,即為前兩個元素與最后一個元素的乘積。
上述兩個結果中的較大值就是答案。注意我們可以不用判斷數組中到底有沒有正數,0 或者負數,因為上述兩個結果實際上已經包含了所有情況,最大值一定在其中。
public class Solution { public int maximumProduct(int[] nums) { Arrays.sort(nums); return Math.max(nums[0] * nums[1] * nums[nums.length - 1], nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]); } }
復雜度分析
時間復雜度:O(NlogN),其中 NN 是數組的長度。
空間復雜度:O(logN),為排序使用的空間。
方法二:線性掃描
在方法一中,我們實際上只要求出數組中最大的三個數以及最小的兩個數,因此我們可以不用排序,用線性掃描直接得出這五個數。
public 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) { // n lies between min1 and min2 min2 = n; } if (n >= max1) { // n is greater than max1, max2 and max3 max3 = max2; max2 = max1; max1 = n; } else if (n >= max2) { // n lies betweeen max1 and max2 max3 = max2; max2 = n; } else if (n >= max3) { // n lies betwen max2 and max3 max3 = n; } } return Math.max(min1 * min2 * max1, max1 * max2 * max3); } }
復雜度分析
-
時間復雜度:O(N)。
-
空間復雜度:O(1)。