数组中的最大连续子数组
暴力,分析法(以一个点固定,减去前面从头开始组成的最小的子数组),动态规划(max=Max(S[i]+a[i+1],a[i+1]))
主要是采用动态规划的方法进行处理,比较简单。
用一个res记录最终结果,表示最大。max为临时的可能的结果。
令a为总数组,也就是你要查找的数组
S代表其中一个子串的加和(假设你已经加到了一定的程度),如果加和加上下一个a[i]还不如a[i]大,那么就让这个a[i]做S这个子
串的开始重新开始。否则就更新S,最后再判断这个值是不是最大的。
代码
#include <iostream>
using namespace std;
int main()
{
int c[100] ;//主数组
int length ;//长度
int res ;
cin >>length ;
for(int i = 0 ; i < length ; i ++ )
{
cin >> c[i];
}
for(int i = 0 ; i <length ; i ++)
{
cout << c[i];
}
int temp_max =c[0];
res = c[0];
for(int i = 1 ; i < length ; i ++)
{
if(c[i]+temp_max>c[i])
{
temp_max = c[i]+temp_max;
}
else {
temp_max = c[i];
}
if(temp_max>res)
{
res = temp_max ;
}
}
cout << res<<endl ;
return 0;
}
欢迎指正。