码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock系列

时间:2016-05-15 00:20:38      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

1、Best Time to Buy and Sell Stock II

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4            if(prices.size() < 1)   //prices.size is unsigned int
 5                 return 0;
 6            int pro = 0;
 7            for(int i=0; i<prices.size()-1; i++)
 8            {
 9                if(prices[i+1] >prices[i])
10                       pro += prices[i+1]-prices[i];
11            }
12            return pro;
13     }
14 };

实际股票是不可能知道今天以后的票价,否则就会根据走向趋势,每次取谷底与山顶就可以了。

 

2、Best Time to Buy and Sell Stock with Cooldown

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int n = prices.size(); 
 5         if(n < 2) 
 6             return 0;
 7         vector<int> sells(n, 0);
 8         vector<int> buys(n, 0);
 9         int delay = 0;
10         sells[0] = 0;
11         buys[0] = -prices[0];
12         sells[1] =  prices[1]-prices[0];
13         buys[1] =  -prices[1];
14         int res = max(0, prices[1]-prices[0]);
15         for(int i=2; i<n; ++i)
16         {
17             delay = prices[i]-prices[i-1];
18             buys[i] = max(sells[i-2]-prices[i], buys[i-1]-delay);
19             sells[i] = max(buys[i-1]+prices[i], sells[i-1]+delay);
20             if(res <sells[i])
21                   res = sells[i];
22         }
23         return res;
24     }
25 };

分析见:http://bookshadow.com/weblog/2015/11/24/leetcode-best-time-to-buy-and-sell-stock-with-cooldown/

 

3、

 

Best Time to Buy and Sell Stock系列

标签:

原文地址:http://www.cnblogs.com/daocaorenblog/p/5494006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!