Codeforces Round #613 B.Just Eat It!(最大连续子区间)

/*
求数组的某连续区间和最大问题
时间复杂度:O(n)
相关例题:HDU 1231(最大连续子序列)
         Codeforces 1285B(Just Eat It!)
*/

样例:
input:
6
1 -3 9 2 -10 8
output:
11

求最大连续子区间板子:

#include<iostream>
#include<string.h>
using namespace std;
#define INF 0x3f3f3f3f
int a[10000];
int main()
{
	int n;
    while(~scanf("%d", &n)){
        for(int i = 0; i < n; i++){
            cin>>a[i];
        }
        int sum=0;
        int maxsum = -1*INF;//区间为负情况
        for(int i = 0; i < n; i++)
		{
            sum += a[i];
            maxsum = max(sum, maxsum);
            if(sum < 0)	sum = 0;
        }
        cout<<maxsum<<endl;
    }
	return 0;
}

 Codeforces 1285B(Just Eat It!)

/*
链接:http://codeforces.com/problemset/problem/1285/B
尺取求最大连续子区间,两个人的max进行比较
尺取:1~n-1 and 2~n
原因:第二个人不能买全部东西 
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 200010;
ll a[maxn];
int main() {
    ll t, n;
    scanf("%lld", &t);
    while (t--) {
        scanf("%lld", &n);
        ll sum = 0;
        for (int i = 0; i < n; i++) {
            scanf("%lld", &a[i]);
            sum += a[i];
        }
        ll maxsum = a[0], maxhere = a[0];
        for (int i = 1; i < n - 1; i++) {
            if (maxhere <= 0) maxhere = a[i];
            else maxhere += a[i];
            maxsum = max(maxhere, maxsum);
        }
        maxhere = a[1];
        ll Max = a[1];
        for (int i = 2; i < n; i++) {
            if (maxhere <= 0) maxhere = a[i];
            else maxhere += a[i];
            Max = max(Max, maxhere);
        }
        if (max(Max, maxsum) >= sum) printf("NO\n");
        else printf("YES\n");
    }
    return 0;
}
发布了39 篇原创文章 · 获赞 27 · 访问量 4104

猜你喜欢

转载自blog.csdn.net/qq_43381887/article/details/104029371