Buy Low Sell High

Buy Low Sell High

Buy Low Sell High

题解:反悔贪心

买股票,一天要么买进,要么卖出,要么什么也不干,求最大利润,首先我们很显然知道了这是一道反悔贪心的题目,我们选择全部买入,但是关键点在于我们怎么反悔

9
10 5 4 7 9 12 6 2 10
比如说这个样例,明显从5买入,12卖出优于从5买入,7卖出,但是我们优先队列是看到有差价可赚我们就会去卖出啊,我们该怎么反悔,很简单我们只要把7再买入一次即可,因为我们发现7-5=2,10-7=3,10-5=(10-7)+(7-5),所以我们看似买入两次7实际上一次7确实是买入,但是另一次我们是为了后面反悔做准备,实际上是为遇到更大的差价做跳板而已
#include <bits/stdc++.h>
#define Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0)
#define all(x) (x).begin(), (x).end()
#define endl 'n'
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-9;
const int N = 3e5 + 10;
priority_queue<ll, vector<ll>, greater<ll>> q;
int main(void)
{
    Zeoy;
    int t = 1;
    // cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        ll sum = 0;
        for (int i = 1; i <= n; ++i)
        {
            ll x;
            cin >> x;
            if (!q.size() || x <= q.top())
            {
                q.push(x);
            }
            else if (q.size() && x > q.top())
            {
                sum += x - q.top();
                q.pop();
                q.push(x);
                q.push(x);
            }
        }
        cout << sum << endl;
    }
    return 0;
}

原文链接: https://www.cnblogs.com/Zeoy-kkk/p/17032018.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Buy Low Sell High

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/310268

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午11:27
下一篇 2023年2月16日 上午11:27

相关推荐