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
给出一个数组,找出其中3个数,使乘积最大
思路:
假如有两个数,乘积最大的是两个最大正数的积或者两个最小负数的积
那么3个数的情况下,最大乘积的即为最大的数 与 其余两个数的最大乘积 的积
这时需要找出数组中最大的数 和 其余两个最大的数和最小的数
可对数组排序,或者直接找到最大的三个数和最小的两个数
这里用排序
public int maximumProduct(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int n = nums.length;
int max1 = nums[0] * nums[1] * nums[n-1];
int max2 = nums[n-3] * nums[n-2] * nums[n-1];
return Math.max(max1, max2);
}
寻找数组中乘积最大的三个数
该博客介绍了一个寻找整数数组中三数之积最大的算法。通过排序数组,可以快速找到最大值、次大值和最小值,从而得到最大乘积。核心思想是利用两个最大正数或两个最小负数的乘积来最大化三数乘积。
476

被折叠的 条评论
为什么被折叠?



