Stock Trading with Cooldown

Problem

The array holds a stock price for each day. You may buy and sell as many times as you like, but you hold at most one share, and after a sale you must wait one full day before you can buy again (the cooldown day). Print the largest total profit.

Constraints

  • 1 <= n <= 5000
  • 0 <= price <= 1000

Examples

Input

5
1 2 3 0 2

Output

3

Solutions

Best approachTime O(n)Space O(1)

Each day the trader is in exactly one of three states, and each state comes from a few states of the day before. This gives the rule for the cooldown without any extra loops.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Best profit.
 * Input   : The prices.
 * Output  : The profit.
 * Approach: Three-state DP
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: Three states after each day. hold: owns a share. sold: sold today. rest: owns nothing, free to buy.
        long hold = Long.MIN_VALUE / 2;
        long sold = 0;
        long rest = 0;
        for (int price : a) {
            // Step 2: Hold: keep holding, or buy today (only from rest, because sold today means the cooldown).
            long newHold = Math.max(hold, rest - price);
            // Step 3: Sold: sell the share that was held until yesterday.
            long newSold = hold + price;
            // Step 4: Rest: stay free, either from rest or the day after a sale.
            long newRest = Math.max(rest, sold);
            hold = newHold;
            sold = newSold;
            rest = newRest;
        }
        return Math.max(sold, rest);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. Why can buy only come from the rest state?