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:
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 <= 50000 <= prices[i] <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the absolute maximum profit from buying and selling a stock with a cooldown period, the brute force approach imagines trying every single combination of actions day by day. By exploring every possible timeline of buying, selling, or waiting, you can calculate the profit for each path and simply pick the highest one at the very end.
Here's how the algorithm would work step-by-step:
def max_profit(prices):
def explore_timelines(current_day, holding_status):
if current_day >= len(prices):
return 0
# Branch into choices because we must evaluate every possible trading timeline
do_nothing_profit = explore_timelines(current_day + 1, holding_status)
if holding_status:
# Sell the stock today and enforce cooldown by skipping the next day
sell_profit = prices[current_day] + explore_timelines(current_day + 2, False)
return max(do_nothing_profit, sell_profit)
else:
# Buy the stock today and transition into holding state
buy_profit = -prices[current_day] + explore_timelines(current_day + 1, True)
return max(do_nothing_profit, buy_profit)
# Start exploring from the very first day with no stock currently held
return explore_timelines(0, False)Instead of checking every single combination of buying and selling, the optimal approach tracks the best possible money situation at each day based on what action you just took. By keeping track of a few distinct financial states as you move forward in time, you can make the most profitable decisions without doing redundant work.
Here's how the algorithm would work step-by-step:
def max_profit(stock_prices):
if not stock_prices:
return 0
holding_share = -stock_prices[0]
sold_share = 0
free_to_buy = 0
# Track maximum wealth across distinct financial states as time moves forward
for current_price in stock_prices[1:]:
previous_holding = holding_share
holding_share = max(holding_share, free_to_buy - current_price)
# Cashing in profit requires holding a share yesterday
sold_share = previous_holding + current_price
# Mandatory cooling off or resting maintains the best free state
free_to_buy = max(free_to_buy, sold_share)
# Final outcomes without holding shares yield the maximum profit
return max(sold_share, free_to_buy)| Case | How to Handle |
|---|---|
| Empty or null price array | Return zero profit immediately since no transactions can be made. |
| Array with a single element | Return zero profit because buying and selling requires at least two distinct days. |
| Array with exactly two elements where the second is greater than the first | Buy on day zero and sell on day one to capture the single profitable transaction without violating cooldown constraints. |
| Strictly monotonically decreasing prices | Maintain zero profit as no profitable selling opportunity ever arises. |
| Strictly monotonically increasing prices | Buy, sell, cooldown, and repeat whenever prices rise, capturing multiple intermediate profits instead of just the endpoints. |
| Large input size up to the maximum constraints | Use an O(n) dynamic programming approach with constant space to efficiently handle large arrays without exceeding time or memory limits. |
| Prices with all identical values | Yield zero profit since no price differential exists between days. |
| Inputs with extreme boundary values near the integer limits | Use standard 32-bit or 64-bit integers where cumulative profit calculations will not overflow given standard financial constraints. |