您的位置:首页 > 其它

[LeetCode 121] - 买入与卖出股票的最佳时机(Best Time to Buy and Sell Stock)

2013-06-20 22:34 537 查看

问题

假设你有一个数组,其中的第i个元素表示一只股票在第i天的价格。

如果只允许你完成一次交易(即买入并卖出股票一次),设计一个找出最大利润的算法。

初始思路

和122一样,基于买入与卖出股票的最佳时机III中的分析很容易得出答案。由于只允许进行一次交易,本题更加简单,我们只需按III中的方法不断更新最大利润即可。

class Solution {
public:
int maxProfit(std::vector<int> &prices)
{
return CaculateProfit(prices).profit;
}

private:
struct Profit
{
Profit() : profit(0), buyPrice(-1), buyDay(0), sellDay(0)
{
}

int profit;
int buyPrice;
int buyDay;
int sellDay;
};

Profit CaculateProfit(std::vector<int> &prices)
{
Profit currentProfit;
Profit maxProfit;

for(int day = 0; day < prices.size(); ++day)
{
if(currentProfit.buyPrice == -1)
{
currentProfit.buyPrice = prices[day];
currentProfit.buyDay = day;
continue;
}

currentProfit.profit = prices[day] - currentProfit.buyPrice;
currentProfit.sellDay = day;

if(currentProfit.profit < 0)
{
currentProfit.buyPrice = prices[day];
currentProfit.buyDay = day;
currentProfit.profit = 0;
}

if(currentProfit.profit > maxProfit.profit)
{
maxProfit = currentProfit;
}
}

return maxProfit;
}
};


maxProfit
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐