865D - Buy Low Sell High 贪心 想法

题意

有N天,每天股票有一个价格p[i]。

第i天你可以有三种选择。

1.买一支股票。

2.卖一支股票。

3.什么也不干。

问最后能获得的最大收益。

题解

什么也不干可以转换为当天买当天卖。

由于a-b + b - c等价于a - c,我们可以引出中转站思想。

可以假设每天都卖了股票,然后把-p[i]入队两次。

第一次被弹出表示作为中转站。

第二次被弹出则表示卖出。

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <bitset>
#include <map>
#include <vector>
#include <stack>
#include <set>
#include <unordered_set>
#include <cmath>
#ifdef LOCAL
#define debug(x) cout<<#x<<" = "<<(x)<<endl;
#else
#define debug(x) 1;
#endif

#define chmax(x,y) x=max(x,y)
#define chmin(x,y) x=min(x,y)
#define lson id<<1,l,mid
#define rson id<<1|1,mid+1,r
#define lowbit(x) x&-x
#define mp make_pair
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<ll, int> pii;

const int MOD = 1e9 + 7;
const double eps = 1e-10;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fll;
const int MAXN = 1e6 + 5;
const int mod = 1e9 + 7;

int a[MAXN];

int main() {
#ifdef LOCAL
    freopen ("input.txt", "r", stdin);
#endif
    int n;
    cin >> n;
    priority_queue<int> q;
    ll ans = 0;
    for(int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        q.push(-a[i]);
        q.push(-a[i]);
        ans += a[i] + q.top();
        q.pop();
    }
    printf("%lld\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/c6376315qqso/article/details/82054587