数组的子数组之和的最大值和下标的开始与结束

本文介绍了一种算法用于在一维数组中查找子数组和的最大值及其对应的开始和结束下标。通过从数组末尾开始遍历,使用变量记录当前最大和及其位置,该算法有效解决了子数组和最大化问题。

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

题目描述:给一个一维数组求其子数组之和的最大值的系列值并求出开始下标和结束下标。

思路;从数组的最后一个数字开始操作,刚开始的时候,让最大值max为最后一个数组的值,并设置一个变量maxStart也等于最后一个数组的值,然后从数组的最后开始往前操作

然后让maxStart与各个数组的值相加,当maxStart小于0时让其等于0,当maxStart大于Max时让max等于maxStart,直到遍历数组的结束。


package com.qetch.interview;
/*
 * 求数组的子数组之和的最大值
 * 最大值的开始和结束的下标
 */
public class MaxSequeArray {
	static int start;//子数组的开始下标
	static int end;//子数组的结束下标
	public static int maxSum(int[] arr){
		int max;
		int len=arr.length;
		int maxStart=arr[len-1];
		max=arr[len-1];
		for(int i=len-2;i>=0;i--){
			  if(maxStart<0){
				  maxStart=0;
				  end=i;
			  }
			  maxStart+=arr[i];
			  if(maxStart>max){
				start=i;
			    max=maxStart;
			  }
		}
		return max;
	}
    public static void main(String[] args) {
		int[] arr={2,5,3,-6,4,-8,6};
		System.out.println(MaxSequeArray.maxSum(arr));
		//end=end-1;
		System.out.println("start="+start+",end="+end);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值