您的位置:首页 > 其它

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

2014-05-28 20:17 113 查看
题目描述:给一个一维数组求其子数组之和的最大值的系列值并求出开始下标和结束下标。

思路;从数组的最后一个数字开始操作,刚开始的时候,让最大值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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐