最大连续子序列的和问题

qinshudong 2012-04-15 04:34:25
看如下 算法


maxsofar=0
maxendinghere=0
for(i=0,i!=n,i++)
{

maxendinghere=max(maxendingher+x【i】,0);
maxsofar=max(maxsofar,maxendinghere);

}

妈妈的 各位作何感想O(n)
...全文
323 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
闲谈共视 2012-04-16
  • 打赏
  • 举报
回复
这个循环的截止到i<=n-1,又因为i的初值赋予0所以其的时间复杂度就是o(n)没有错的啊!!!
freud.wy 2012-04-16
  • 打赏
  • 举报
回复
如果给定的序列是全负的话貌似返回的是0啊。
DeDeWo 2012-04-16
  • 打赏
  • 举报
回复
再路过一下,表示好奇,lz的算法的实现代码如下:
lz再修改下吧

//sample input
//4
//2 -1 3 1
//sample output
//5
// 答案有误
#include<iostream>
#include<cstring>
using namespace std;
int main(){
int a[100],n;
while(scanf("%d",&n)==1 && n){
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int m=0,ans=0;
for(int i=0;i<n;i++){
m=max(m+a[i],0);
ans=max(ans,m);
}
printf("%d\n",ans);
}
system("pause");
return 0;
}


DeDeWo 2012-04-16
  • 打赏
  • 举报
回复
LZ V5
yubinyuleo 2012-04-15
  • 打赏
  • 举报
回复
表示看不懂
昵称很不好取 2012-04-15
  • 打赏
  • 举报
回复
挺好的啊,简单

33,007

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧