#include <stdio.h>
#include <windows.h>
# define MAX(a, b) ((a) > (b) ? (a) : (b))
int MaxSubSum1(int * a, int n);
int MaxSubSum2(int * a, int n);
int main(void){
int a[] = {-1, 3, 2, -3, 4, 5, -2, 1};
int n = sizeof(a)/sizeof(int);
printf("%d\n", MaxSubSum1(a, n));
printf("%d\n", MaxSubSum2(a, n));
system("pause");
return 0;
}
int MaxSubSum1(int * a, int n){
if(NULL == a || 0 == n)
return 0;
//dp[i]是以a[i]为末尾的最大连续子序列和
int * dp = (int*)malloc(n * sizeof(int));
int max = dp[0] = a[0];
for(int i = 1; i < n; i++){
if(dp[i-1] <= 0)
dp[i] = a[i];
else
dp[i] = dp[i-1] + a[i];
max = MAX(max, dp[i]);
}
free(dp);
return max;
}
int MaxSubSum2(int * a, int n){
if(NULL == a || 0 == n)
return 0;
int dp = a[0];
int max = dp;
for(int i = 1; i < n; i++){
if(dp <= 0)
dp = a[i];
else
dp = dp + a[i];
max = MAX(max, dp);
}
return max;
}