309. Best Time to Buy and Sell Stock with Cooldown
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 1
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==1)return 0;
vector<int> s0(prices.size(), 0);
vector<int> s1(prices.size(), 0);
vector<int> s2(prices.size(), 0);
s0[0] = 0;
s1[0] = -prices[0];
s2[0] = INT_MIN;//lower base case
for(int i=1; i<prices.size(); i++){
s0[i] = max(s0[i-1], s2[i-1]);
s1[i] = max(s1[i-1], s0[i-1]-prices[i]);
s2[i] = s1[i-1] + prices[i];
}
return max(s2[prices.size()-1], s0[prices.size()-1]);
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
spatial complexity
:
O
(
n
)
O(n)
O(n)
solution 2
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==1)return 0;
int s0 = 0, s1 = -prices[0], s2 = INT_MIN;
int t0,t1,t2;
for(int i=1; i<prices.size(); i++){
t0 = s0, t1 = s1, t2 = s2;
s0 = max(t0, t2);
s1 = max(t1, t0-prices[i]);
s2 = t1 + prices[i];
}
return max(s0, s2);
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
spatial complexity
:
O
(
1
)
O(1)
O(1)
solution 3
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==1)return 0;
int s0 = 0, s1 = -prices[0], s2 = INT_MIN;
for(int i=1; i<prices.size(); i++){
int tmp = s0;
s0 = max(s0, s2);
s2 = s1 + prices[i];
s1 = max(s1, tmp-prices[i]);
}
return max(s0, s2);
}
};
time complexity
:
O
(
n
)
O(n)
O(n)
spatial complexity
:
O
(
1
)
O(1)
O(1)
NOTE
the illustration above is the state transition diagram of this problem, there are three states, according to the actions you can take.
after we get the state transition diagram, we can write the state transition equation
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