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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值