買賣股票系列
【leetcode】40-best-time-to-buy-and-sell-stock 力扣 121. 買賣股票的最佳時機
【leetcode】41-best-time-to-buy-and-sell-stock-ii 力扣 122. 買賣股票的最佳時機 II
【leetcode】42-best-time-to-buy-and-sell-stock-iii 力扣 123. 買賣股票的最佳時機 III
【leetcode】43-best-time-to-buy-and-sell-stock-iv 力扣 188. 買賣股票的最佳時機 IV
【leetcode】44-best-time-to-buy-and-sell-stock-with-cooldown 力扣 309. 買賣股票的最佳時機包含冷凍期
【leetcode】45-best-time-to-buy-and-sell-stock-with-cooldown 力扣 714. 買賣股票的最佳時機包含手續費
開源地址
為了便于大家學習,所有實現均已開源。歡迎 fork + star~
122. 買賣股票的最佳時機 II
給你一個整數數組 prices ,其中 prices[i] 表示某支股票第 i 天的價格。
在每一天,你可以決定是否購買和/或出售股票。你在任何時候 最多 只能持有 一股 股票。你也可以先購買,然后在 同一天 出售。
返回 你能獲得的 最大 利潤 。
示例 1:
輸入:prices = [7,1,5,3,6,4]
輸出:7
解釋:在第 2 天(股票價格 = 1)的時候買入,在第 3 天(股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5 - 1 = 4。
隨后,在第 4 天(股票價格 = 3)的時候買入,在第 5 天(股票價格 = 6)的時候賣出, 這筆交易所能獲得利潤 = 6 - 3 = 3。
最大總利潤為 4 + 3 = 7 。
示例 2:
輸入:prices = [1,2,3,4,5]
輸出:4
解釋:在第 1 天(股票價格 = 1)的時候買入,在第 5 天 (股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5 - 1 = 4。
最大總利潤為 4 。
示例 3:
輸入:prices = [7,6,4,3,1]
輸出:0
解釋:在這種情況下, 交易無法獲得正利潤,所以不參與交易可以獲得最大利潤,最大利潤為 0。
提示:
1 <= prices.length <= 3 * 10^4
0 <= prices[i] <= 10^4
v1-上一題的思路延續
上一題
class Solution {
public int maxProfit(int[] prices) {
int maxResult = 0;
int minVal = prices[0];
for(int i = 0; i < prices.length; i++) {
minVal = Math.min(minVal, prices[i]);
maxResult = Math.max(prices[i] - minVal, maxResult);
}
return maxResult;
}
}
思路
因為可以無限次,獲取所有上升的區間利潤即可。
改造一下
public int maxProfit(int[] prices) {
int maxResult = 0;
// int minVal = prices[0];
for(int i = 1; i < prices.length; i++) {
// minVal = Math.min(minVal, prices[i]);
maxResult += Math.max(prices[i] - prices[i-1], 0);
}
return maxResult;
}
v2-性能優化
思路
下面的方式實現會更好一些。
代碼
class Solution {
public int maxProfit(int[] prices) {
// 因為知道每一天的利潤,所以直接第二天高于今天,直接累加利潤
int maxProfit = 0;
for(int i = 1; i < prices.length; i++) {
if(prices[i] > prices[i-1]) {
maxProfit += prices[i] - prices[i-1];
}
}
return maxProfit;
}
}
效果
0ms 擊敗 100.00%
44.51MB 擊敗93.87%
V3-DP 的思路
思路
我們可以通過一個數組記錄每一次操作的最大利潤。
b[n]
s[n]
每一次操作都可以決定是否操作。
遞推公式
// 是否賣出? 不賣; 賣出=上一次買入 + 當前價格
// 是否買? 不買; 買入=上一次賣出-當前價格
代碼
public int maxProfit(int[] prices) {
int buy[] = new int[prices.length];
int sell[] = new int[prices.length];
buy[0] = -prices[0];
for(int i = 1; i < prices.length; i++) {
// 是否賣出? 不賣; 賣出=上一次買入 + 當前價格
sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i]);
// 是否買? 不買; 買入=上一次賣出-當前價格
buy[i] = Math.max(buy[i-1], sell[i-1] - prices[i]);
}
return sell[prices.length-1];
}
小結
完整的思路,只看對應的波動的山坡上升的地方。
不過 dp 的思路是通用解法,我們理解之后,更方便我們優化。
參考資料
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/