【算法面试题】数组中三个数的最大乘积

【算法面试题】数组中三个数的最大乘积

1.要求:

1.整型数组nums,在数组中找出由三个数字组成的最大乘积,并输出这个乘积。
2.乘积不会越界。
3.重点考察:线性扫描。

2.问题分析

1.数组元素全部为正数,三个数的最大乘积就是最大的三个数相乘。
2.数组元素全部为正数,三个数的最大乘积也是最大的三个数乘积。
例如 -4、-3、-2、-1。最大数就是(-3 * -2 * -1)。
3.数组元素有正数有负数,三个数的最大乘积就是最小的两位数乘于最大的那位数
例如:-4、-3、-2、3、6、8、9。最大数就是(-4 * -3 *9)。
1、2视为一种情况,三是一种情况,因此只需要比较两种情况的数值,输出数值最大的那个。

3.第一种写法

public class MaxProduct {
	public static void main(String[] args) {
		System.out.println(sort(new int[]{7,5,6,0,7,6}))
	}
	public static int sort(int[] nums){
		Arrays.sort(nums);//排序
		int n = nums.length;
		return Math.max(nums[0] * nums[1] * nums[n-1], nums[n-3] * nums[n-2] * nums[n-1])
	}
}

3.1第一种写法缺点

时间复杂度太大: O(N*log2N)

4.第二种写法

public class MaxProduct {
	public static void main(String[] args) {
		System.out.println(getMaxMin(new int[]{7,5,6,0,7,6}));
	}
	public static int getMaxMin(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 i = 0; i < nums.length; i++) {
			if(nums[i] < min1){
				min2 = min1;
				min1 = nums[i];
			}else if(nums[i] < min2){
				min2 = nums[i];
			}
			if(nums[i] > max1){
				max3 = max2;
				max2 = max1;
				max1 = nums[i];
			}else if(nums[i] > max2){
				max3 = max2;
				max2 = nums[i];
			}else if(nums[i] > max3){
				max3 = nums[i];
			}
		}
		return Math.max(min1 * min2 * max1, max1 * max2 * max3);
	}
}

4.1第二种写法优势

时间复杂度小:O(N)。

5.输出结果

代码输出结果

6.总结

本题使用线性扫描算法,时间复杂度更小,省了排序的时间。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Katakuri1125

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值