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

问题

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

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

 

初始思路

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

 1 class Solution {
 2     public:
 3         int maxProfit(std::vector<int> &prices)
 4         {
 5             return CaculateProfit(prices).profit;
 6         }
 7         
 8     private:
 9         struct Profit
10         {
11             Profit() : profit(0), buyPrice(-1), buyDay(0), sellDay(0)
12             {
13             }
14             
15             int profit;
16             int buyPrice;
17             int buyDay;
18             int sellDay;
19         };
20         
21         Profit CaculateProfit(std::vector<int> &prices)
22         {
23             Profit currentProfit;
24             Profit maxProfit;
25             
26             for(int day = 0; day < prices.size(); ++day)
27             {
28                 if(currentProfit.buyPrice == -1)
29                 {
30                     currentProfit.buyPrice = prices[day];
31                     currentProfit.buyDay = day;
32                     continue;
33                 }
34                 
35                 currentProfit.profit = prices[day] - currentProfit.buyPrice;
36                 currentProfit.sellDay = day;
37                 
38                 if(currentProfit.profit < 0)
39                 {
40                     currentProfit.buyPrice = prices[day];
41                     currentProfit.buyDay = day;
42                     currentProfit.profit = 0;
43                 }
44                 
45                 if(currentProfit.profit > maxProfit.profit)
46                 {
47                     maxProfit = currentProfit;
48                 }
49             }
50 
51             return maxProfit;
52         }
53     };
maxProfit

 

posted @ 2013-06-20 22:34  Shawnone  阅读(558)  评论(0编辑  收藏  举报