forked from CaiFengGH/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
``` |