首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

最大连续子序列和有关问题

2012-10-26 
最大连续子序列和问题问题描述:给定一个序列a[1],a[2]...a[n],求解其连续子序列中元素和的最大值例如: 6 -

最大连续子序列和问题
问题描述:给定一个序列a[1],a[2]...a[n],求解其连续子序列中元素和的最大值
例如: 6 -1 5 4 -7 这个序列最大连续子序列和为14
具体问题见: HDOJ 1003  TZU 1202
这个问题在《数据结构与算法分析--c语言描述》(weiss著)中文版第13页(英文版第18页)中也有描述。在第21页给出了一个算法程序:

#include <stdio.h>#include <limits.h>#define MAX 100000+100int main(void){  int n;  int m;  int a[MAX];  int i,j;  int thisSum,maxSum;  int maxStart,maxEnd,thisStart;  scanf("%d",&n);  for(i = 1; i <= n; i++)    {      scanf("%d",&m);      for(maxStart=maxEnd=thisStart=thisSum=0,maxSum=INT_MIN,j = 0; j < m; j++)    {      scanf("%d",&a[j]);      thisSum += a[j];      if(thisSum > maxSum)        {          maxSum = thisSum;          maxStart = thisStart;          maxEnd = j;        }      if(thisSum < 0)        {          thisSum = 0;          thisStart = j+1;        }    }      if(i > 1)    printf("\n");      printf("Case %d:\n",i);      printf("%d %d %d\n",maxSum,maxStart+1,maxEnd+1);    }  return 0;}

程序主要部分还是上面的算法,只是加上了对子序列首尾索引号的处理。

热点排行