1. dp[i][0] 表示第i天持有股票所得最多现金 ,
dp[i][1] 表示第i天不持有股票所得最多现金
2. dp[i][0] = max(dp[i - 1][0], -prices[i]); 前一天持有的收益,与今天持有的max
dp[i][1] = max(dp[i - 1][1], prices[i] + dp[i - 1][0]); 前一天不持有的收益与今天卖出的max
3. dp[0][0] -= prices[0];
dp[0][1] = 0;
4. 从前向后遍历
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i=1; i
递推公式发生了变化,如下,只有dp[i][0]不同
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0]=-prices[0];
dp[0][1] =0;
for(int i=1; i
1. dp[i][j]中 i表示第i天,j为 [1 - 4] 四个状态,dp[i][j]表示第i天状态j所剩最大现金。
2. dp[i][1] = max(dp[i-1][0] - prices[i], dp[i - 1][1]);
dp[i][2] = max(dp[i - 1][1] + prices[i], dp[i - 1][2])
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
3. dp[0][1] = -prices[0];
dp[0][2] = 0;
dp[0][3] = -prices[0];
dp[0][4] = 0;
4. 从前向后遍历
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][5];
dp[0][1]=-prices[0];
dp[0][2]=0;
dp[0][3]=-prices[0];
dp[0][4]=0;
for(int i=1; i
这里的规律就是状态[1~2K],奇数就是买入(持有),偶数就是卖出(不持有)
class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
int[][] dp=new int[n][2*k+1];
for(int i=1; i<2*k; i+=2){
dp[0][i]=-prices[0];
}
for(int i=1; i
单独列出一个状态的归类为「不持有股票的状态」,因为本题有冷冻期,而冷冻期的前一天,只能是 「今天卖出股票」状态。如果是 「不持有股票状态」那么就很模糊,因为不一定是 卖出股票的操作。
dp[0][0] = -prices[0]; dp[0][1]=0; dp[0][2]=0; dp[0][3]=0
从前向后遍历
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][4];
dp[0][0] = -prices[0];
for(int i=1; i
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0]=-prices[0];
for(int i=1; i