Problem:

Analysis:
DP is like induction prove.
- define the base case
- define the inductive rule

Code:
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) return 0;
int n = prices.length;
int[] hold = new int[n];
int[] unhold = new int[n];
hold[0] = - prices[0];
hold[1] = Math.max(-prices[0], -prices[1]);
unhold[0] = 0;
unhold[1] = Math.max(hold[0]+prices[1], 0);
for (int i=2; i<n; i++){
hold[i] = Math.max(unhold[i-2] - prices[i], hold[i-1]);
unhold[i] = Math.max(hold[i-1] + prices[i], unhold[i-1]);
}
return unhold[n-1];
}
本文介绍了一种使用动态规划解决股票买卖问题的方法,通过定义持有和未持有股票两种状态,实现寻找股票买卖的最佳时机以获得最大利润。代码示例清晰展示了状态转移的过程。
682

被折叠的 条评论
为什么被折叠?



