?LeetCode刷題實(shí)戰(zhàn)309:最佳買(mǎi)賣(mài)股票時(shí)機(jī)含冷凍期
After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
你不能同時(shí)參與多筆交易(你必須在再次購(gòu)買(mǎi)前出售掉之前的股票)。
賣(mài)出股票后,你無(wú)法在第二天買(mǎi)入股票 (即冷凍期為 1 天)。
示例
輸入: [1,2,3,0,2]
輸出: 3
解釋: 對(duì)應(yīng)的交易狀態(tài)為: [買(mǎi)入, 賣(mài)出, 冷凍期, 買(mǎi)入, 賣(mài)出]
解題
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if(len <= 1) return 0;
int[][] dp = new int[len][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[1][0] = Math.max(dp[0][0], dp[0][1] + prices[1]);
dp[1][1] = Math.max(dp[0][0] - prices[1], dp[0][1]);
for(int i = 2; i < len; i++) {
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);//這次要手上沒(méi)有股票
dp[i][1] = Math.max(dp[i-2][0] - prices[i], dp[i-1][1]);//那么上場(chǎng)進(jìn)行了交易要休息一天
}
return dp[len-1][0];
}
}
LeetCode1-280題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)301:刪除無(wú)效的括號(hào)
