Buy Low Sell High CodeForces - 867E (思维,贪心)

大意: 第i天可以花$a_i$元买入或卖出一股或者什么也不干, 初始没钱, 求i天后最大收益

考虑贪心, 对于第$x$股, 如果$x$之前有比它便宜的, 就在之前的那一天买, 直接将$x$卖掉.

并不需要计算出最优的卖出时间, 因为若$x$后有更优价格, 可以再买回$x$, 不影响贪心结果

#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstdio>
#include <queue>
#define REP(i,a,n) for(int i=a;i<=n;++i)

using namespace std;
typedef long long ll;

const int N = 4e5+10, INF = 0x3f3f3f3f;
int a[N], n, m, k, t;
vector<int> g[N];

int main() {
    scanf("%d", &n);
    priority_queue<int,vector<int>,greater<int> > q;
    ll ans = 0;
    REP(i,1,n) {
        int t;
        scanf("%d", &t);
        q.push(t);
        if (t>q.top()) {
            ans += t-q.top();
            q.pop();
            q.push(t);
        }
    }
    printf("%lld\n", ans);
}

猜你喜欢

转载自www.cnblogs.com/uid001/p/10344820.html