【LeetCode+51nod】股票低买高卖N题

【121】Best Time to Buy and Sell Stock (2018年11月25日重新复习)

给一个数组代表股票每天的价格,只能有一次交易,即一次买入一次卖出,求最大收益。

题解:用一个变量维护此时的最大收益和最小成本。遍历数组求值。

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int minPrice = INT_MAX;
 5         int maxProfit = 0;
 6         for (auto ele : prices) {
 7             minPrice = min(ele, minPrice);
 8             maxProfit = max(maxProfit, (ele - minPrice));
 9         }
10         return maxProfit;
11     }
12 };
View Code

 2018年11月25日,这次一次 AC 了。

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         const int n = prices.size();
 5         if (n < 2) {return 0;}
 6         int buy = prices[0], sell = 0;
 7         int ret = 0;
 8         for (int i = 1; i < n; ++i) {
 9             sell = prices[i];
10             if (buy < sell) {
11                 ret = max(sell - buy, ret);
12             } else {
13                 buy = prices[i];
14             }
15         }
16         return ret;
17     }
18 };
View Code

 

【122】 Best Time to Buy and Sell Stock II (2018年11月25日复习)

这题是给了一个数组代表股票每天的价格,可以做任意次的交易,但是不能同时持有多支股票。(每次的操作方式只能是先买,然后卖了,再买。不能在卖了之前再次买入。)

题解:这题我是用了贪心,每次发现今天的价格比昨天的价格高,就在昨天买入,今天卖出。

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

还可以用dp解答,dp通用一些。以后那些变种都是dp的变种。

 

【123】Best Time to Buy and Sell Stock III (2018年11月30日,复习)

给了一个数组代表每天股票的价格,只能做两次交易,问最大的盈利是多少。(还跟原来的条件是一样的,不支持同时持有多股票,每次操作方式都是先买,卖了,然后才能再买。)

题解:这题我用了类似动态规划这种做法,状态其实很简单,四个状态,分别代表第一次买入后的钱,第一次卖出后的钱,第二次买入后的钱,第二次卖出后的钱。最后这四个数可能都是负数,这个时候不买最好了。 

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         const int n = prices.size();
 5         if (n == 0) {return 0;}
 6         vector<int> g(4, INT_MIN);
 7         g[0] = -prices[0];
 8         for (int i = 1; i < n; ++i) {
 9             g[0] = max(g[0], -prices[i]);
10             g[1] = max(g[1], g[0]+prices[i]);
11             g[2] = max(g[2], g[1]-prices[i]);
12             g[3] = max(g[3], g[2]+prices[i]);
13         }
14         return max(0, max(g[1], g[3]));
15     }
16 };
View Code

 

 

【188】 Best Time to Buy and Sell Stock IV

 

【309】 Best Time to Buy and Sell Stock with Cooldown

 

【714】 Best Time to Buy and Sell Stock with Transaction Fee

 

posted @ 2018-11-30 20:33  zhangwanying  阅读(424)  评论(0编辑  收藏  举报