风口的猪-中国牛市
大意
给你已知n天的股票的价格,然后可以进行两次买入和卖出的机会,买第二次的时候,手里不能持有第一次买的股票,问最大收益是多少
思路
在注释上
class Solution {
public:
/**
* 计算你能获得的最大收益
*
* @param prices Prices[i]即第i天的股价
* @return 整型
*/
int calculateMax(vector<int> prices) {
const int INF = 1<<30;
int firstBuy = INF;
int firstSell = -INF;
int secondBuy = -INF;
int secondSell = -INF;
int len=prices.size();
for(int i=0;i<len;++i)
{
firstBuy = min(firstBuy,prices[i]);
//第一次买入的时候,应该是当前价格最低的那支股票
firstSell = max(firstSell,prices[i]-firstBuy);
//第一次卖出的时候,应该是max{第i天股票的价格-之前价格最低的那只股票}
secondBuy = max(secondBuy,firstSell-prices[i]);
//第二次买入的时候,应该是max{当前收益即firstSell-当前股票价格},也就是说当前买入价格越低越好
secondSell = max(secondSell,secondBuy+prices[i]);
//第二次卖出的时候,应该是max{第二次买入后的收益-当前股票价格的最大值}
}
return secondSell;
}
};
也可以暴力来一发
class Solution {
public:
/**
* 计算你能获得的最大收益
*
* @param prices Prices[i]即第i天的股价
* @return 整型
*/
int calculateMax(vector<int> prices) {
const int maxn = 1e2+1;
int INF = 1<<30;
int len=prices.size();
int ans = -INF;
for(int i=0;i<len;++i)
{
for(int j=i+1;j<len;++j)
{
int temp=prices[j]-prices[i];
if(temp>ans)
{
ans=temp;
}
for(int m=j+1;m<len;++m)
{
for(int n=m+1;n<len;++n)
{
temp=prices[j]-prices[i]+prices[n]-prices[m];
if(temp>ans)
{
ans=temp;
}
}
}
}
}
if(ans<0) return 0;
return ans;
}
};