原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]
题解:
与Best Time to Buy and Sell Stock相似.
有三个状态s0, s1, s2. s0 buy stock 变成s1, s1 sell stock 变成s2.
s0[i] = max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if(prices == null || prices.length == 0){ 4 return 0; 5 } 6 int len = prices.length; 7 int [] s0 = new int[len]; 8 int [] s1 = new int[len]; 9 int [] s2 = new int[len]; 10 11 s0[0] = 0; 12 s1[0] = -prices[0]; 13 s2[0] = 0; 14 for(int i = 1; i<len; i++){ 15 s0[i] = Math.max(s0[i-1],s2[i-1]); 16 s1[i] = Math.max(s1[i-1], s0[i-1]-prices[i]); 17 s2[i] = s1[i-1] + prices[i]; 18 } 19 return Math.max(s0[len-1], s2[len-1]); 20 } 21 }
Reference: https://leetcode.com/discuss/72030/share-my-dp-solution-by-state-machine-thinking
时间: 2024-10-14 11:58:59