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
Constraints:
1 <= prices.length <= 5000
0 <= prices[i] <= 1000
class Solution:
def maxProfit(self, prices: List[int]) -> int:
f1, f2, f3 = -prices[0], 0, 0
for price in prices[1:]:
pf1, pf2, pf3 = f1, f2, f3
f1 = max(pf1, pf3 - price)
f2 = max(pf2, pf1 + price)
f3 = max(pf3, pf2)
return f2
class Solution {
public int maxProfit(int[] prices) {
int f1 = -prices[0], f2 = 0, f3 = 0;
for (int i = 1; i < prices.length; ++i) {
int pf1 = f1, pf2 = f2, pf3 = f3;
f1 = Math.max(pf1, pf3 - prices[i]);
f2 = Math.max(pf2, pf1 + prices[i]);
f3 = Math.max(pf3, pf2);
}
return f2;
}
}
class Solution {
public:
int maxProfit(vector<int>& prices) {
int f1 = -prices[0], f2 = 0, f3 = 0;
for (int i = 1; i < prices.size(); ++i) {
int pf1 = f1, pf2 = f2, pf3 = f3;
f1 = max(pf1, pf3 - prices[i]);
f2 = max(pf2, pf1 + prices[i]);
f3 = max(pf3, pf2);
}
return f2;
}
};
func maxProfit(prices []int) int {
f1, f2, f3 := -prices[0], 0, 0
for i := 1; i < len(prices); i++ {
pf1, pf2, pf3 := f1, f2, f3
f1 = max(pf1, pf3-prices[i])
f2 = max(pf2, pf1+prices[i])
f3 = max(pf3, pf2)
}
return f2
}
func max(a, b int) int {
if a > b {
return a
}
return b
}