Codeforces 867 D. Buy Low Sell High (贪心)

博客给出Codeforces 865D题目的链接,题目是预测未来N天某股票价格,每天可买、卖或不操作,初始无股票且不能卖空,结束时也无股票,求最大获利。解题思想是采用贪心算法,最小数小就加差值并放入2倍值,考虑当前卖掉情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://codeforces.com/problemset/problem/865/D

题意:You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.

给你n个点,每个点可以买,可以卖(前提你有东西),问你最后获利是多少。

思想:直接贪心就行,只要最小的比你小,你就加上这一部分,然后将2倍的放进来。考虑当前卖掉,如果没有比这个数大,那就是卖掉了,如果有的话,那么插入的2个数的第一个数就是一个过渡,直接求差值扔掉就行。

#include<bits/stdc++.h>
using namespace std;
multiset<int>M; 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin>>n;
	long long ans=0;
	for(int i=0;i<n;i++)
	{
		int temp;
		cin>>temp;
		if(!M.empty() && *M.begin()<temp)
		{
			ans=ans+(long long)(temp-*M.begin());
			M.erase(M.begin());
			M.insert(temp);
			M.insert(temp);
		}
		else
			M.insert(temp);
	}
	cout<<ans<<endl;
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值