Problem A: 最大連續區間和
Time Limit: 1 Sec Memory Limit: 32 MBSubmit: 43 Solved: 2
[Submit][Status]
Description
你的任務是找出一串數字中,哪一些連續數字之和最大,並輸出這個和。
例如:輸入的一串數字爲“-1 2 -3 4 2 -5 6 -5”,你需要輸出“7”(在該輸入中,和最大的一些連續數字爲“4 2 -5 6”)。
Input
第一行爲測試用例的組數。
每組輸入包括兩行,第一行爲一串數的個數n (n<=10^5)。
隨後一行爲該串數字,每兩個數中間會用空格隔開。(題目保證每個數的絕對值小於10^9)
Output
對每一組測試用例,輸出最大和是多少
Sample Input
Sample Output
HINT
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
//const int MAXN = 100000 + 5;
typedef long long ll;
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
int n;
scanf("%d", &n);
ll maxn=0, temp=0;//maxn爲最大連續數字之和,temp爲當前連續數字之和
for (int i = 0; i <n; i++)
{
int c;
scanf("%d", &c);
if (i == 0)
{
maxn = c;
if (c < 0)temp = 0;
else temp = c;
}
else
{
temp += c;
if (temp>maxn)maxn = temp;
else if (temp < 0)temp = 0;//假設temp爲前i個數字和,因爲temp爲0,那麼前i+1個的最大數字和一定是第i+1個數字
}
}
printf("%lld\n", maxn);
}
return 0;
}
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
typedef long long ll;
const int MAXN = 100000 + 5;
ll r[MAXN];//用r[i]表示以第i個數字結尾的最大連續數字和,r數組中最大的數即爲結果。
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
memset(r, 0, sizeof(r));
int n;
scanf("%d",&n);
for (int i = 0; i <n; i++)
{
ll c;
scanf("%lld",&c);
if (i==0) r[i] = c;
else
r[i] =max(c,c+r[i-1]);
}
sort(r,r+n,cmp);
printf("%lld\n",r[0]);
}
return 0;
}