Leetcode 309. Best Time to Buy and Sell Stock with Cooldown
You are given an array where prices[i]
is the price of a given stock on the i-th
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 constraints:
prices
is non-empty?
To achieve the maximum profit given the constraints, the problem can be approached using dynamic programming. We will maintain three states:
Using these states, the transitions between days can be described as:
The optimal solution will involve iterating through the prices array and updating the states according to these transitions.
#include <vector>
#include <algorithm>
class Solution {
public:
int maxProfit(std::vector<int>& prices) {
if (prices.empty()) return 0;
int n = prices.size();
// Initialize dp arrays
std::vector<int> hold(n, 0);
std::vector<int> sell(n, 0);
std::vector<int> cool(n, 0);
hold[0] = -prices[0]; // On day 0, if we hold a stock, the profit is negative of the price
for (int i = 1; i < n; ++i) {
hold[i] = std::max(hold[i - 1], cool[i - 1] - prices[i]);
sell[i] = hold[i - 1] + prices[i];
cool[i] = std::max(cool[i - 1], sell[i - 1]);
}
// The result will be the maximum profit on the last day after selling or being in cooldown
return std::max(sell[n - 1], cool[n - 1]);
}
};
Initialization: Start by initializing the hold
, sell
, and cool
vectors for day 0. hold[0]
is initialized to -prices[0]
because if we buy the stock on the first day, our profit becomes negative of that day’s price.
hold[i-1]
or buying a new stock after a cooldown (cool[i-1] - prices[i]
).hold[i-1] + prices[i]
).cool[i-1]
) or entering cooldown from a sell (sell[i-1]
).sell
or cool
state.The time complexity is ( O(n) ) because we iterate through the prices array exactly once, updating the states in constant time for each day. The space complexity is ( O(n) ) due to the storage of dynamic programming arrays hold
, sell
, and cool
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?