边工作边刷题:70天一遍leetcode: day 32
Best Time to Buy and Sell Stock with Cooldown
要点:这题就是house robber的变形,buy/sell来记录,一个trick是buy就是profit损失,这样后面的sell就能catch up。另外,这里cooldown体现在buy的递推式:取sell[i-2],因为sell[i-1]可能就在i-1这个点卖的。
错误点:
- 注意buy和sell的初始化:buy[1]是前两个哪个prices点低
- buy可以为负,sell最小为0。最后返回的就是sell[n-1]
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
if(n==0) return 0;
int[] buy = new int[n+1];
int[] sell = new int[n+1];
buy[0] = 0;
buy[1] = -prices[0];
sell[0] = 0;
sell[1] = 0;
for(int i = 2; i<=n; i++) {
buy[i] = Math.max(buy[i-1], sell[i-2]-prices[i-1]);
sell[i] = Math.max(sell[i-1], buy[i-1]+prices[i-1]);
}
return sell[n];
}
}