题意翻译
题目:
已知接下来N天的股票价格,每天你可以买进一股股票,卖出一股股票,或者什么也不做.N天之后你拥有的股票应为0,当然,希望这N天内能够赚足够多的钱.
输入:
第一行一个整数天数N(2<=N<=300000).
第二行N个数字p1,p2...pN(1<=pi<=10^6),表示每天的价格.
输出: N天结束后能获得的最大利润.
样例解释:
样例1:分别在价格为5,4,2的时候买入,分别在价格为9,12,10的时候卖出,总利润为−5−4+9+12−2+10=20−5−4+9+12−2+10=20 . 翻译贡献者UID:36080
输入输出样例
输入 #1复制
9 10 5 4 7 9 12 6 2 10
输出 #1复制
20
输入 #2复制
20 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4
输出 #2复制
41
说明/提示
In the first example, buy a share at 55 , buy another at 44 , sell one at 99 and another at 1212 . Then buy at 22 and sell at 1010 . The total profit is −5−4+9+12−2+10=20−5−4+9+12−2+10=20 .
解析:
如果我们要使得利息最大,当然是买入和卖出的差要尽可能打,就是 有利息可以赚就卖,不然就别卖进来;
这个可以同优先队列进行存储;
1、如果有比当前价格还低的就卖出去赚差价。注意要塞入当前价格,因为你不能确定后面的是否更好。
比如:当前几个为 5 ,而你已经买入了3,它先会算5-3 = 2这个差价,ans += 2,当后面遇到 7时,7-3 更为划算,这时可以时,7-5 =2 ,ans+= 2;因为前面ans加了 2,相当于买个 3卖了7;
#include <bits/stdc++.h>
using namespace std;
#define int long long
int read() {
int ret = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') f = (ch == '-') ? -f : f, ch = getchar();
while (ch >= '0' && ch <= '9') ret = ret * 10 + ch - '0', ch = getchar();
return ret * f;
}
int n, ans;
priority_queue<int, vector<int>, greater<int> > q;
signed main() {
n = read();
for (int i = 1; i <= n; ++i) {
int k = read();
if (!q.empty() && q.top() < k) ans += k - q.top(), q.pop(), q.push(k);
q.push(k);
}
printf("%lld\n", ans);
return 0;
}
时间复杂度:O(n*log2n);