1.最大子列和问题
1. 代码如下:在线处理——O(N)
#include <stdio.h>
int MaxSubseqSum4(int A[], int N){
int ThisSum, MaxSum;
int i;
ThisSum = MaxSum = 0;
for(i=0; i<N; i++){
ThisSum += A[i];
if(ThisSum > MaxSum)
MaxSum = ThisSum;
else if(ThisSum < 0)
ThisSum = 0;
}
return MaxSum;
}
int main(){
int a, N;
scanf("%d\n", &N);
int List[N];
for(int i=0; i<N; i++){
scanf("%d", &a);
List[i] = a;
}
int max = MaxSubseqSum4(List, N);
printf("%d\n", max);
return 0;
}
2. 其他解法
2.1 O(N^3)
#include <stdio.h>
int MaxSubseqSum1(int A[], int N){
int ThisSum, MaxSum = 0;
int i, j, k;
for(i=0; i<N; i++){
for(j=i; j<N; j++){
ThisSum = 0;
for(k=i; k<=j; k++)
ThisSum += A[k];
if(ThisSum > MaxSum)
MaxSum = ThisSum;
}
}
return MaxSum;
}
int main(){
int a, N;
scanf("%d\n", &N);
int List[N];
for(int i=0; i<N; i++){
scanf("%d", &a);
List[i] = a;
}
int max = MaxSubseqSum1(List, N);
printf("%d\n", max);
return 0;
}
2.2 分而治之
#include <stdio.h>
int Max3(int a, int b, int c){
return a>b ? a>c ? a : c : b>c ? b :c;
}
int DivideAndConquer(int List[], int left, int right){
int MaxLeftSum, MaxRightSum; /*存放左右子问题的解*/
int MaxLeftBorderSum, MaxRightBorderSum; /*存放跨分界线的结果*/
int LeftBorderSum, RightBorderSum;
int center, i;
if(left == right){
if(List[left]>0)
return List[left];
else
return 0;
}
/*下面为"分"*/
center = (left + right) / 2;
/*递归求得两边的最大和*/
MaxLeftSum = DivideAndConquer(List, left, center);
MaxRightSum = DivideAndConquer(List, center+1, right);
/*求跨分界线的最大子列和*/
MaxLeftBorderSum = 0;
LeftBorderSum = 0;
/*从中线向左扫描*/
for(i=center; i>=left; i--){
LeftBorderSum += List[i];
if(LeftBorderSum > MaxLeftBorderSum)
MaxLeftBorderSum = LeftBorderSum;
}
MaxRightBorderSum = 0;
RightBorderSum = 0;
/*从中线向右扫描*/
for(i=center+1; i<=right; i++){
RightBorderSum += List[i];
if(RightBorderSum > MaxRightBorderSum)
MaxRightBorderSum = RightBorderSum;
}
/*下面返回"治"的结果*/
return Max3(MaxLeftSum, MaxRightSum, MaxLeftBorderSum+MaxRightBorderSum);
}
int MaxSubseqSum3(int List[], int N){
return DivideAndConquer(List, 0, N-1);
}
int main(){
int a, N;
scanf("%d\n", &N);
int List[N];
for(int i=0; i<N; i++){
scanf("%d", &a);
List[i] = a;
}
int max = MaxSubseqSum3(List, N);
printf("%d\n", max);
return 0;
}
运行结果如下: