【LeetCode+51nod】股票低買高賣N題

【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 };
View Code

 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 };
View Code

 

【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 };
View Code

還能夠用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 };
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

相關文章
相關標籤/搜索