文章目錄
題目描述
- 股票系列!這次加入了冷凍期要素,需要考慮更多的狀態
思路 && 代碼
- 每天,都有三個狀態:開一個 dp = int[n][3] 二維數組
- 主要思路…就是理解幾種狀態,以及轉移的思路(見注釋)
- 時空復雜度:O(n)、O(n)
class Solution {public int maxProfit(int[] prices
) {int[][] dp
= new int[prices
.length
][3];dp
[0][0] = -prices
[0]; dp
[0][1] = 0; dp
[0][2] = 0; for(int i
= 1; i
< prices
.length
; ++i
) {dp
[i
][0] = Math.max(dp
[i
- 1][0], dp
[i
- 1][1] - prices
[i
]); dp
[i
][1] = Math.max(dp
[i
- 1][1], dp
[i
- 1][2]); dp
[i
][2] = dp
[i
- 1][0] + prices
[i
]; }return Math.max(dp
[prices
.length
- 1][1], dp
[prices
.length
- 1][2]); }
}
class Solution {public int maxProfit(int[] prices
) {int[][] dp
= new int[prices
.length
][3];dp
[0][0] = -prices
[0]; dp
[0][1] = 0; dp
[0][2] = 0; for(int i
= 1; i
< prices
.length
; ++i
) {dp
[i
][0] = Math.max(dp
[i
- 1][0], dp
[i
- 1][1] - prices
[i
]); dp
[i
][1] = Math.max(dp
[i
- 1][1], dp
[i
- 1][2]); dp
[i
][2] = dp
[i
- 1][0] + prices
[i
]; }return Math.max(dp
[prices
.length
- 1][1], dp
[prices
.length
- 1][2]); }
}
二刷
- 代碼量少的一,就 9 行!但是難度還是有。
- 我覺得難點在于狀態的考慮,但是理清狀態之后,或許就很難做錯了= =
class Solution {public int maxProfit(int[] prices
) {int[][] dp
= new int[prices
.length
][3]; dp
[0][0] = -prices
[0]; dp
[0][1] = 0; dp
[0][2] = 0; for(int i
= 1; i
< prices
.length
; i
++) {dp
[i
][0] = Math.max(dp
[i
- 1][1] - prices
[i
], dp
[i
- 1][0]); dp
[i
][1] = Math.max(dp
[i
- 1][1], dp
[i
- 1][2]); dp
[i
][2] = dp
[i
- 1][0] + prices
[i
]; }return Math.max(dp
[prices
.length
- 1][1], dp
[prices
.length
- 1][2]);}
}
總結
以上是生活随笔為你收集整理的【LeetCode笔记】309. 最佳买卖股票时机含冷冻期(Java、动态规划)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。