[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
相关文章推荐
- [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- [LeetCode 123] - 买入与卖出股票的最佳时机III(Best Time to Buy and Sell Stock III)
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- 最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售卖时(动态规划,数组,模拟)
- LeetCode WIith JS || 121. Best Time to Buy and Sell Stock[求股票的最佳收益,只能交易一次]
- Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售卖时(动态规划,数组,模拟)
- leetcode 121.Best Time to Buy and Sell Stock 股票买卖最佳时间
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机
- [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机
- LeetCode 121. Best Time to Buy and Sell Stock (买卖股票的最好时机)
- [Leetcode] Best time to buy and sell stock 买卖股票的最佳时机