第i天的操作只有三种:没有操作,买入,卖出。
由于最多只能同时持有一只股票,所以第i天各自操作的收益是
1、没有操作:第i天的买入收益=第i-1天的买入收益,第i天的卖出收益=第i-1天的卖出收益
2、买入操作:第i天的买入收益=第i-1天的卖出收益-第i天的价格
3、卖出操作:第i天的卖出收益=第i-1天的买入收益+第i天的价格
状态转移方程如下:(遍历所有的天数)
todayBuy = max(yesterdayBuy,yesterdaySell-prices[today]);
todaySell = max(yesterdaySell,yesterdayBuy+prices[today]);
public int maxProfit (int[] prices) { int buy=Integer.MIN_VALUE, sell=0; for(int i=0 ;i<prices.length; i++){ int curbuy = Math.max(buy, sell-prices[i]); sell = Math.max(buy+prices[i], sell); buy = curbuy; } return sell; }