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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/passer__/article/details/82055020

题目链接: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;
} 

猜你喜欢

转载自blog.csdn.net/passer__/article/details/82055020