309. Best Time to Buy and Sell Stock with Cooldown
题目链接:https://leetcode.com/problems...
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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。