package practice;
/**
* @author iu
* 连续子数组的最大和
* 给出一个数组,找出数组中连续的最大和的子数组
* 使用max记录最大值,sum记录累加的当前值,如果sum <= 0 sum重新赋值为 array[i]
* 如果 >= 0 则继续相加,但是需要比较sum和 max的值, max记录的是之前最大的值。
* 如果当前sum大于 max 则 max = sum
*/
public class FindGreatestSumOfSubArray {
public static int findGreatestSumOfSubArray(int[] arrray) {
if (arrray.length < 1 || arrray == null) {
return 0;
}
int sum = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < arrray.length; i++) {
if (sum <= 0) {
sum = arrray[i];
} else {
sum += arrray[i];
}
if (sum > max) {
max = sum;
}
}
return max;
}
public static void main(String[] args) {
int[] array = {1,-2,-3,-4,5,4,3,-1,2,5,3,-10,-5,2,4};
int max = findGreatestSumOfSubArray(array);
System.out.println(max);
}
}