标签:
#include <stdio.h> int MaxSub(int A[],int N){ return MaxSubSeq(A,0, N-1); } int Max3(int x, int y, int z){ if(x > y){ if(x > z){ return x; } else{ return z; } } else{ if(y > z){ return y; } else{ return z; } } } int MaxSubSeq(int A[],int Left,int Right){ int MaxLeftSum,MaxRightSum; int MaxLeftBorderSum,MaxRightBorderSum; int LeftBorderSum,RightBorderSum; if(Left == Right){ if(A[Left] > 0){ return A[Left]; } else return 0; } int Mid = (Left + Right)/2; MaxLeftSum = MaxSubSeq(A,Left,Mid); MaxRightSum = MaxSubSeq(A,Mid+1, Right); MaxLeftBorderSum = 0;LeftBorderSum = 0; int i; for(i = Mid; i >= Left ; i--){ LeftBorderSum += A[i]; if(LeftBorderSum > MaxLeftBorderSum){ MaxLeftBorderSum = LeftBorderSum; } } MaxRightBorderSum = 0; RightBorderSum = 0; for(i = Mid+1; i<= Right; i++){ RightBorderSum += A[i]; if(RightBorderSum > MaxRightBorderSum){ MaxRightBorderSum = RightBorderSum; } } return Max3(MaxLeftSum,MaxRightSum, (MaxLeftBorderSum + MaxRightBorderSum)); } int main(){ int K; int i; scanf("%d",&K); int Arr[K]; for(i = 0 ; i< K; i++){ scanf("%d",&Arr[i]); } printf("%d",MaxSub(Arr,K)); return 0; }
给定K个整数组成的序列{ N?1??, N?2??, ..., N?K?? },“连续子列”被定义为{ N?i??, N?i+1??, ..., N?j?? },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
6
-2 11 -4 13 -5 -2
20
标签:
原文地址:http://www.cnblogs.com/yangRyoung/p/4830178.html