LeetCode-每日一題-309
阿新 • • 發佈:2020-07-10
題目
給定一個整數陣列,其中第i個元素代表了第i天的股票價格 。
設計一個演算法計算出最大利潤。在滿足以下約束條件下,你可以儘可能地完成更多的交易(多次買賣一支股票):
你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。
賣出股票後,你無法在第二天買入股票 (即冷凍期為 1 天)。
輸入: [1,2,3,0,2] 輸出: 3 解釋: 對應的交易狀態為: [買入, 賣出, 冷凍期, 買入, 賣出]
思路:
動態規劃
1.對於 profit[i][0],我們目前持有的這一支股票可以是在第 i -1 天就已經持有的,對應的狀態為 profit[i-1][0];或者是第 i 天買入的;
2. 對於 profit[i][1],第 i 天賣出的;
3. 對於 profit[i][2],可以是第 i - 1天賣出的收益,也可以是第 i-1 天不持有股票且不在冷凍期的收益。
class Solution { public int maxProfit(int[] prices) { if(prices.length==0) return 0; int[][] profit = new int[prices.length][3]; profit[0][0] = -prices[0];// f[i][0]: 手上持有股票的最大收益 // f[i][1]: 手上不持有股票,並且處於冷凍期中的累計最大收益 // f[i][2]: 手上不持有股票,並且不在冷凍期中的累計最大收益 for(int i=1;i<prices.length;++i) { profit[i][0] = Math.max(profit[i-1][0], profit[i-1][2]-prices[i]); profit[i][1] = profit[i-1][0]+prices[i]; profit[i][2] = Math.max(profit[i-1][1], profit[i-1][2]); } return Math.max(profit[prices.length-1][1], profit[prices.length-1][2]); } }