Maximum Product of Three Numbers
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Constraints:
3 <= nums.length <= 104
-1000 <= nums[i] <= 1000
思路一:对给定的数组排序后完全分类,数组只可能出现三种情况
- 在零轴中间
- 全部位于零轴左边
- 全部位于零轴右边
所以只要判断数组左右乘积最大值即可
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int max = nums[0] * nums[1] * nums[nums.length - 1];
max = Math.max(nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3], max);
return max;
}
思路二:对思路一可以进行优化,不用对数组进行全部排序,只需要取最大的三个值和最小的三个值判断
标签:nums,int,max,628,length,easy,Output,Input,leetcode From: https://www.cnblogs.com/iyiluo/p/16936829.html