Skip to content

Commit

Permalink
achieve maxSubGroup
Browse files Browse the repository at this point in the history
  • Loading branch information
CaiFengGH authored Aug 30, 2017
1 parent b1d5b03 commit 42caa0a
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions CodingInterview/31-连续子数组最大和.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
>题目描述
数组中一个或者连续多个整数组成一个子数组,求所有子数组的和的最大值;

- 实现方法

一个数字前面数字之和为0或者负数,则前面的数字和累积无效,重新开始求和;

一个数字前面数字之和为正数,则先暂时保存当前值,与后面求和的结果进行比较;

```
/**
* @author Ethan
* @desc 和最大的子数组
*/
public class MaxSubGroup {
/**
* @desc 寻找和最大的子数组
* @param arr
*/
public int maxSubGroup(int[] arr){
//异常输入
if(arr == null){
System.out.println("数组为空请重新输入");
}
//初始化当前和 最大和
int currentSum = 0;
int maxSum = 0;
//数组开始的索引
int start = 0;
int end = 0;
for(int i = 0; i < arr.length; i++){
//如果当前和为非正数,则前面积累无效
if(currentSum <= 0){
currentSum = arr[i];
start = i;
}else{
currentSum += arr[i];
}
//记录最大值
if(currentSum > maxSum){
maxSum = currentSum;
end = i;
}
}
System.out.println("最大数组的索引为:"+start+"->"+end);
return maxSum;
}
/**
* @desc 测试
*/
public static void main(String[] args) {
int[] arr = {1,-2,3,10,-4,7,2,-5};
MaxSubGroup max = new MaxSubGroup();
int res = max.maxSubGroup(arr);
System.out.println("子数组的最大和为:"+res);
}
}
```

0 comments on commit 42caa0a

Please sign in to comment.