309. Best Time to Buy and Sell Stock with Cooldown
题目链接:
dp来解,要用两个dp array分别表示现在的操作是buy还是sell,优化空间用滚动数组,或者几个int
public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; /* buy[i] = Math.max(sell[i-2]-prices[i], buy[i-1]) * sell[i] = Math.max(sell[i-1], buy[i-1] + prices[i]) */ int preBuy = Integer.MIN_VALUE, curBuy = Integer.MIN_VALUE; int preSell = 0, curSell = 0; for(int price : prices) { preBuy = curBuy; curBuy = Math.max(preSell - price, preBuy); preSell = curSell; curSell = Math.max(preSell, preBuy + price); } return curSell; }}