All problems

Problem 456

Stock Trading with Cooldown

Medium · 20 pts · Array, Dynamic Programming

Problem

You know a stock's price for each of N days. You may complete as many transactions as you like (buy one share, then sell it later), holding at most one share at a time. After you sell, you must wait one full day (a cooldown) before you can buy again. Find the maximum total profit. Track three states for each day: holding a share, just sold (in cooldown), and resting without a share.

Input

First line: N. Second line: N prices.

Output

Print the maximum profit.

Constraints

1 <= N <= 5000; 0 <= price <= 1000

Example input

5
1 2 3 0 2

Example output

3

Explanation

With prices 1 2 3 0 2: buy on day 1 and sell on day 2 (profit 1), cool down on day 3, then buy on day 4 at 0 and sell on day 5 at 2 (profit 2). The total is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Last Stone Weight II Next: Domino and Tromino Tiling