# 309. Best Time to Buy and Sell Stock with Cooldown
Question link is here.
# Question
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
- After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
Example 2:
Input: prices = [1]
Output: 0
# Solution
This is an DP question. Say that the length of prices is .
We use DP[i] to denote the max profit from to .
And the transition equation is:
where
Explaination:
is the profit that we make when we buy at i and sell at j. dp[j+2] is the max profit we make from to . j+2 is because after we sell at j, we need to cool down at j+1, and we can only start buying at j+2.
is for we don't do any operation.
# Java
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
int[] dp = new int[length + 2];
for(int i = length - 1; i >= 0; i--) {
int maxSell = 0;
for(int j = i+1; j < length; j++) {
int profit = (prices[j] - prices[i]) + dp[j + 2];
maxSell = Math.max(maxSell, profit);
}
int noOp = dp[i + 1];
dp[i] = Math.max(maxSell, noOp);
}
return dp[0];
}
}
# Python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp = [0] * (len(prices) + 2)
for i in range(len(prices) - 1, -1, -1):
maxSell = 0
for j in range(i+1, len(prices)):
maxSell = max(maxSell, prices[j] - prices[i] + dp[j+2])
noOp = dp[i+1]
dp[i] = max(maxSell, noOp)
return dp[0]
Time Complexity .