最大子列和问题

给定K个整数组成的序列{ N1, N2, …, NK },“连续子列”被定义为{ Ni, Ni+1, …, Nj },其中 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

int MaxSubseqSum1(int List[], int N)
{
   int i,j,k;
   int ThisSum;int MaxSum=0;
   for(i=0;ifor(j=i;j0;
             for(k=i;kif(ThisSum>MaxSum)
               MaxSum = ThisSum;
          }
     }
   return MaxSum;
}

算法2:部分存储中间值的穷举 O(N^2)

int MaxSubseqSum2(int List[], int N)
{
   int i,j,k;
   int ThisSum;int MaxSum=0;
   for(i=0;i0;
      for(j=i;jif(ThisSum>MaxSum)
               MaxSum = ThisSum;
          }
     }
   return MaxSum;
}

算法3:分而治之 O(NlogN)

#include 
#include 
#include 
using namespace std;
long long max(long long a,long long b,long long c){
   return a>b?(a>c?a:c):(b>c?b:c);
}

long long maxSubSeqSum(const vector<int> &a,int left ,int right){
   if(left == right){
     if(a[left]>0)
         return a[left];
     else 
         return 0;    
   }
int mid = (left + right)/2;
long long maxLeftSum = maxSubSeqSum(a,left,mid);
long long maxRightSum = maxSubSeqSum(a,mid+1,right);
long long maxLeftBorderSum = 0,leftBorderSum=0;
for(int i=mid;i>=left;--i){
      leftBorderSum+=a[i];
      if(leftBorderSum>maxLeftBorderSum)
        maxLeftBorderSum=leftBorderSum;
}
long long maxRightBorderSum=0,rightBorderSum=0;
for(int i=mid+1;i<=right;++i){
  rightBorderSum+=a[i];
  if(rightBorderSum>maxRightBorderSum)
      maxRightBorderSum=rightBorderSum;
}
return max(maxLeftSum,maxRightSum,maxLeftBorderSum+maxRightBorderSum);
}

int main(){
   vector<int> a;
   int k,x;
   scanf("%d",&k);
   for(int i=0;icin>>x;
         a.push_back(x);
   }
   printf("%lld\n",maxSubSeqSum(a,0,a.size()-1));
   return 0;
}

算法4:在线处理 O(N)

#include 
#define MAXN 1000001
long long maxSubSeqSum4(int a[],int n)
{
  long long maxSum=0,thisSum=0;
  for(int i=0;iif(thisSum>maxSum)
         maxSum = thisSum;
    else if(thisSum<0){
        thisSum=0;   
    }     
  }
  return maxSum;
}

int main (void){
    int k;int a[MAXN];
    printf("please input the nums\n");
    scanf("%d", &k);
    for(int i=0;iscanf("%d", &a[i]);
    }
    printf("%lld\n",maxSubSeqSum4(a,k));
    return 0;
}

你可能感兴趣的:(数据结构1)