Given an integer array, find three numbers whose product is maximum and output the maximum product.輸入一個大小大於等於三的數組,給出其中任意三個數乘積中的最大乘積算法
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24數組
public int maximumProduct(int[] nums) { Integer max1 = Integer.MIN_VALUE;Integer max2 = max1;Integer max3 = max1; Integer min1 = Integer.MAX_VALUE;Integer min2 = min1; for(int num : nums){ if(num > max1){ max3 = max2; max2 = max1; max1 = num; }else if(num > max2){ max3 = max2; max2 = num; }else if(num > max3){ max3 = num; } if(num < min1){ min2 = min1; min1 = num; }else if(num < min2){ min2 = num; } } return Math.max(max1*max2*max3, max1*min1*min2); }
public int maximumProduct(int[] nums) { Arrays.sort(nums); int a = nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3]; int b = nums[0] * nums[1] * nums[nums.length - 1]; return a > b ? a : b; }