LeetCode-Maximum Product Subarray

本文讨论解决最大连续子数组乘积问题的方法,通过分析数组中的负数分布和处理0的情况,优化算法实现。从暴力遍历到正确考虑边界条件,最终成功通过测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Maximum Product Subarray

   

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

该题做的泪流满面,第一次暴力遍历一个爆长的case超时,

仔细观察后发现其实乘积是有规律的,只需要考虑数组中负数的个数,和处理出现0的情况即可。

写代码的过程中,由于多次考虑不周全,导致出现Wrong Answer。改了N次之后终于AC

	public static int maxProduct(int[] A) {
		int total = 0 ,econdSegmentTotal = 0 ,firstSegmentTotal = 0 ;
		int negetiveCount = 0;
		int startElementPos = 0;int secondElementPos = 0;
		int result = A[0];

		for(int i = 0; i < A.length ; ++i){

			if(A[i] == 0){
				if(result < total){
					result = total;
				}
				if(result < 0){
					result = 0;
				}
				startElementPos = i+1;
				secondElementPos = i+1;
				negetiveCount = 0;
			}else{
				if(A[i] < 0){
					negetiveCount++;
					if(negetiveCount == 1){
						secondElementPos = i+1;
					}
					if(negetiveCount % 2 == 0){
						firstSegmentTotal *= A[i];
						econdSegmentTotal *= A[i];
						total = (total < firstSegmentTotal ? firstSegmentTotal:total); 
					}else{
						econdSegmentTotal *= A[i];
						total = (total < firstSegmentTotal ? firstSegmentTotal:total);
						total = (total < econdSegmentTotal ? econdSegmentTotal:total);
						firstSegmentTotal *= A[i];
					}
				}else{
					firstSegmentTotal *= A[i];
					econdSegmentTotal *= A[i];
					total = (total < firstSegmentTotal ? firstSegmentTotal:total);
					total = (total < econdSegmentTotal ? econdSegmentTotal:total);
				}
				
			}
			if(secondElementPos == i){
				econdSegmentTotal = A[i];
				total = (total < firstSegmentTotal ? firstSegmentTotal:total);
				total = (total < econdSegmentTotal ? econdSegmentTotal:total);
			}
			if(startElementPos == i){
				total = econdSegmentTotal = firstSegmentTotal = A[i];
			}
		}
		return result > total ? result:total;
	}

Submission Result: Accepted

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值