Leetcode buy stocks template problem

 

dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i])
             //max(   选择 rest  ,           选择 sell      )

Explanation: Today I do not hold stocks, there are two possibilities:
either I did not hold yesterday, and then select the rest today, so I did not hold today;
either I hold the stock yesterday, but today I sell, and so I do not hold the stock today.

dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])
             //max(   选择 rest  ,           选择 buy         )

Explanation: Today I hold the stock, there are two possibilities:
either I would hold the stock yesterday, and then select the rest today, so I have to hold the stock today;
either I do not hold this yesterday, but today I choose to buy so today I hold stocks.
Because buying and selling complete a deal so only need to buy or sell a k-1 can be selected

 


Case Base:
DP [-1] [K] [0] = 0
Explanation: Since i is zero, so that i = -1 means that have not yet started, this time, of course 0 profit.
dp [-1] [k] [ 1] = -infinity
explained: When not started, it is impossible to hold the stock, which can not represent a negative infinity.
dp [i] [0] [ 0] = 0
explained: k is because from the beginning, so k = 0 means that the transaction did not allow, at this time of course the profit is zero.
dp [i] [0] [ 1] = -infinity
explained: without allowing the transaction, it is impossible to hold the stock, which can not be expressed with negative infinity

Released eight original articles · won praise 0 · Views 2625

Guess you like

Origin blog.csdn.net/thebs2/article/details/104774623