Codeforces D. Yet Another Yet Another Task (區間和 / 貪心)(Round 88 Div.2)

傳送門

題意: 有一個數組a,找得到其(最大區間和sum - 區間內最大元素maxx)的最大值。
在這裏插入圖片描述

思路: 每次遇到這周大範圍的區間和問題就沒轍,其實都是些很巧妙的思維

  • 因爲答案ans的最小值爲0,所以只需考慮正整數元素;又因元素max可在[1 ,30]範圍,所以可以枚舉maxx值,再枚舉區間即可。
  • 若a[i] > maxx 則不符枚舉目的,sum = 0(放棄前面的區間段)
  • 若sum < 0則不符最大值 >= 0,sum = 0

代碼實現:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;

int n, ans, sum;
int a[N];

signed main()
{
    IOS;

    cin >> n;
    for(int i = 0; i < n; i ++)
        cin >> a[i];
    //枚舉maxx
    for(int maxx = 1; maxx <= 30; maxx ++){
        sum = 0;
        //再枚舉區間
        for(int i = 0; i < n; i ++){
            if(a[i] > maxx){
                sum = 0;
                continue;
            }
            sum += a[i];
            if(sum < 0)
                sum = 0;
            ans = max(ans, sum - maxx);
        }
    }

    cout << ans << endl;

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章