算法提高 数组求和
资源限制时间限制:1.0s 内存限制:256.0MB
问题描述 输入n个数,围成一圈,求连续m(m<n)个数的和最大为多少?
输入格式 输入的第一行包含两个整数n, m。第二行,共n个整数。
输出格式 输出1行,包含一个整数,连续m个数之和的最大值。
样例输入10 3
9 10 1 5 9 3 2 6 7 4
样例输出23
数据规模和约定 0<m<n<1000, -32768<=输入的每个数<=32767。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[2005]={0},N,M,max=0;
//读入N:总的数据长度 和M:连续的数据长度
cin>>N>>M;
//读入所有数据
for(int i=0;i<N;i++)
{
cin>>a[i];
}
//把连续的数据从头放到数据的最后(使之成为一个圈)
for(int i=0;i<M;i++)
{
a[N+i]=a[i];
}
//遍历数组
for(int i=0;i<N;i++)
{
int sum=0;
//取和 取max
for(int j=i;j<i+M;j++)
{
sum+=a[j];
}
max = max<sum?(sum):(max);
}
cout<<max;
return 0;
}
老了老了,啥也不会了。