Leetcode中股票問題合集
阿新 • • 發佈:2018-12-24
- Best Time to Buy and Sell Stock II
思路:這道題用到了貪心演算法。從第二天開始,只要比前一天大,那說明就掙錢,那麼就前一天買今天賣,掙差價。
int maxProfit(vector<int>& prices) { int res = 0; int n = prices.size(); for (int i = 0; i < n - 1; i++) { if (prices[i] < prices[i+1]) res += prices[i+1] - prices[i]; } return res; }
- Best Time to Buy and Sell Stock III
思路:本身並不是特別懂,可看部落格。
用兩個遞推公式,分別更新兩個變數local和global。定義local[i][j]為在第i天之前最多交易j次,並且最後一天必須交易,獲得的最大利潤,global[i][j]定義為在第i天前最多交易j次,獲得的最大利潤。
local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)
global[i][j] = max(local[i][j], global[i - 1][j])
diff = prices[i+1]-prices[i]
int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int n = prices.size(); int g[n][3] = {0},l[n][3] = {0}; for (int i = 1; i < n; i++) { int diff = prices[i] - prices[i-1]; for (int j = 1; j <= 2; j++) { l[i][j] = max(g[i-1][j-1] + max(diff,0),l[i-1][j]+diff); g[i][j] = max(g[i-1][j],l[i][j]); } } return g[n-1][2]; }
思路2:既然最多買兩次,那麼就分成兩段。第一段求prices[0,i]上最大收益,第二段求prices[i,n-1]上最大收益,然後兩個加起來就可以。求最大收益直接用Best Time to Buy and Sell Stock I中的方法,但是如果寫在同一個迴圈中比如下方程式碼,時間複雜度就是O(n^2)。所以不能用這種方法,同樣的思路,但是要減小時間複雜度,那麼我們先正向掃描,儲存沒天交易的最大收益到陣列,然後反向掃描,儲存每天收益的最小值到陣列,然後再遍歷,以第i天為中心,左右兩邊的收益相減,就是最大收益。
for (int i = 0; i < n; i++) {
p1 = maxProfit(prices[0,i]); //O(n*n)
p2 = maxProfit(prices[i,n-1]); // O(n*n)
max_p = max(p1+p2,max_p);
}
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int n = prices.size();
vector<int> first(n,0);
vector<int> second(n,0);
int min_buy = prices[0];
int res = 0;
for (int i = 1; i < n; i++) {
min_buy = min(min_buy,prices[i]);
first[i] = max(first[i-1],prices[i]-min_buy);
}
int max_buy = prices[n-1];
for (int i = n-2; i >= 0 ; i--) {
max_buy = max(max_buy,prices[i]);
second[i] = min(second[i+1],prices[i] - max_buy);
}
for (int i = 0; i < n; i++) {
res = max(res,first[i]-second[i]);
}
return res;
}
714.Best Time to Buy and Sell Stock with Transaction Fee
思路:這裡多了一個買賣股票需要扣除費用。對於第i天來說,手中要麼沒有股票,要麼手持一個股票。用sold表示第i天沒有股票的收益,hold表示第i天手持股票的收益。
沒有股票的情況:要麼是前一天就沒有股票,要麼是今天賣掉了,所以這種情況下,最大值就是比較這兩者。sold[i] = max(sold[i-1],hold[i-1]+price[i]-fee)
手持股票的情況:要麼是前一天就持有股票,要麼今天買的股票,取其中最大值。
hold[i] = max(hold[i-1],sold[i-1] - price[i])
int maxProfit(vector<int>& prices, int fee) {
int sold = 0,hold = -prices[0];
for (int i = 1; i < prices.size(); i++) {
sold = max(sold,hold + prices[i] - fee);
hold = max(hold,sold - prices[i]);
}
return sold;
}