Algo-Sim › Dynamic Programming

Best Time to Buy and Sell Stock with Cooldown

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Trade as often as you like, but rest a day after every sale. Three states per day (hold, sold, rest) form a small state machine.

Problem

You are given prices, where prices[i] is the price of a stock on day i. You may complete as many transactions as you like (buy one and sell one share, many times), but you may hold at most one share, and after you sell you cannot buy on the next day. Return the maximum profit.

Constraints

Edge cases to test

Follow-up questions

What do the three states mean?
hold (own a share), sold (sold today), rest (free and not cooling down); each updates from yesterday’s states in O(1).
What if the cooldown is k days?
Buying uses the free state from k + 1 days earlier, so keep a short buffer of past values.

Solution

Java

public int maxProfit(int[] prices) {
    int n = prices.length;
    int[] hold = new int[n], sold = new int[n], rest = new int[n];
    hold[0] = -prices[0];
    for (int i = 1; i < n; i++) {
        hold[i] = Math.max(hold[i - 1], rest[i - 1] - prices[i]);
        sold[i] = hold[i - 1] + prices[i];
        rest[i] = Math.max(rest[i - 1], sold[i - 1]);
    }
    return Math.max(sold[n - 1], rest[n - 1]);
}

Python

def max_profit(prices):
    n = len(prices)
    hold, sold, rest = [0] * n, [0] * n, [0] * n
    hold[0] = -prices[0]
    for i in range(1, n):
        hold[i] = max(hold[i - 1], rest[i - 1] - prices[i])
        sold[i] = hold[i - 1] + prices[i]
        rest[i] = max(rest[i - 1], sold[i - 1])
    return max(sold[n - 1], rest[n - 1])

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxProfit(vector<int> &prices) {
        int n = int(prices.size());
        vector<int> hold = vector<int>(n), sold = vector<int>(n), rest = vector<int>(n);
        hold[0] = -prices[0];
        for (int i = 1; i < n; i++) {
            hold[i] = std::max(hold[i - 1], rest[i - 1] - prices[i]);
            sold[i] = hold[i - 1] + prices[i];
            rest[i] = std::max(rest[i - 1], sold[i - 1]);
        }
        return std::max(sold[n - 1], rest[n - 1]);
    }
};

More Dynamic Programming problems