# 最大子序列和的四种算法

1.穷举法

	public static int maxSubSum1(int[] a) {
int maxSum = 0;
int sum;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
sum = 0;
for (int k = i; k <= j; k++) {
sum += a[k];// 计算a[i]到a[j]的和
}
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}

2.对上述第一个算法的改进

	public static int maxSubSum2(int[] a) {
int maxSum = 0;
int sum;
for (int i = 0; i < a.length; i++) {
sum = 0;
for (int j = i; j < a.length; j++) {
sum += a[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
return maxSum;
}

3.分而治之

	// 参数：处理数组，左边界，右边界
public static int maxSubSum3(int[] a, int left, int right) {
if (left == right) {
if (a[left] > 0) {
return a[left];
} else {
return 0;
}
}

int center = (left + right) / 2;
int maxLeftSum = maxSubSum3(a, left, center);
int maxRightSum = maxSubSum3(a, center + 1, right);

int maxLeftBorderSum = 0, leftBorderSum = 0;
for (int i = center; i >= left; i--) {
leftBorderSum += a[i];
if (leftBorderSum > maxLeftBorderSum) {
maxLeftBorderSum = leftBorderSum;
}
}

int maxRightBorderSum = 0, rightBorderSum = 0;
for (int i = center + 1; i <= right; i++) {
rightBorderSum += a[i];
if (rightBorderSum > maxRightBorderSum) {
maxRightBorderSum = rightBorderSum;
}
}

int maxBorderSum = maxLeftBorderSum + maxRightBorderSum;
return maxBorderSum > maxLeftSum ? maxBorderSum > maxRightSum ? maxBorderSum : maxRightSum
: maxLeftSum > maxRightSum ? maxLeftSum : maxRightSum;
}

4.最优起点

	public static int maxSubSum4(int[] a){
int maxSum=0,sum=0;
for(int i=0;i<a.length;i++){
sum+=a[i];
if(sum>maxSum){
maxSum=sum;
}else if(sum<0){
sum=0;
}
}
return maxSum;
}