#include<stdio.h> int MaxSubseqSum1(int A[], int N); int MaxSubseqSum2(int A[], int N); int MaxSubseqSum3(int A[], int N); int Max3(int A, int B, int C); int DevideAndConquer(int A[], int left, int right); int main() { int MaxSum; int A[100000]; int N; int i; scanf("%d", &N); for(i=0; i<N; i++) { scanf("%d", &A[i]); } MaxSum = MaxSubseqSum3(A, N); printf("%d\n", MaxSum); return 0; } 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 MaxSubseqSum2(int A[], int N) { int ThisSum, MaxSum=0; int i, j, k; for(i=0; i<N; i++) { ThisSum = 0; for(j=i; j<N; j++) { ThisSum += A[j]; if(ThisSum > MaxSum) { MaxSum = ThisSum; } } } return MaxSum; } int DevideAndConquer(int A[], int left, int right) { if(left == right) { if(A[left] > 0) { return A[left]; } else { return 0; } } int MaxLeft=0, MaxRight=0, MaxLeftBorderSum=0, MaxRightBorderSum=0, LeftBorderSum=0, RightBorderSum=0; int i=0; int center = (left+right) / 2; MaxLeft = DevideAndConquer(A, left, center); MaxRight = DevideAndConquer(A, center+1, right); for(i=center; i>=left; i--) { LeftBorderSum += A[i]; if(LeftBorderSum > MaxLeftBorderSum) { MaxLeftBorderSum = LeftBorderSum; } } for(i=center+1; i<=right; i++) { RightBorderSum += A[i]; if(RightBorderSum > MaxRightBorderSum) { MaxRightBorderSum = RightBorderSum; } } return Max3(MaxLeft, MaxRight, MaxLeftBorderSum+MaxRightBorderSum); } int MaxSubseqSum3(int A[], int N) { DevideAndConquer(A, 0, N-1); } int Max3(int A, int B, int C) { return A>B ? A>C?A:C : B>C?B:C; }
原文:http://www.cnblogs.com/guyueyue/p/5008583.html