【121】Best Time to Buy and Sell Stock (2018年11月25日从新复习)数组
给一个数组表明股票天天的价格,只能有一次交易,即一次买入一次卖出,求最大收益。ide
题解:用一个变量维护此时的最大收益和最小成本。遍历数组求值。spa
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 };
2018年11月25日,此次一次 AC 了。code
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 };
【122】 Best Time to Buy and Sell Stock II (2018年11月25日复习)blog
这题是给了一个数组表明股票天天的价格,能够作任意次的交易,可是不能同时持有多支股票。(每次的操做方式只能是先买,而后卖了,再买。不能在卖了以前再次买入。)it
题解:这题我是用了贪心,每次发现今天的价格比昨天的价格高,就在昨天买入,今天卖出。io
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 };
还能够用dp解答,dp通用一些。之后那些变种都是dp的变种。event
【123】Best Time to Buy and Sell Stock III (2018年11月30日,复习)class
给了一个数组表明天天股票的价格,只能作两次交易,问最大的盈利是多少。(还跟原来的条件是同样的,不支持同时持有多股票,每次操做方式都是先买,卖了,而后才能再买。)变量
题解:这题我用了相似动态规划这种作法,状态其实很简单,四个状态,分别表明第一次买入后的钱,第一次卖出后的钱,第二次买入后的钱,第二次卖出后的钱。最后这四个数可能都是负数,这个时候不买最好了。
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 };
【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