Python coding

Trading profit with a rest day

prices[i] is the price of a share on day i. You may trade as often as you like, but you own at most one share at a time: buy it on one day, sell it on a later day, then you may buy again. After each sale you must rest for one day, so if you sell on day i you can't buy on day i + 1. Return the largest total profit you can make; not trading at all earns 0.

prices has 0 to 5,000 values, each from 0 to 10,000. Aim for one pass and O(1) extra space.

Besides the tests, one large input (4,000 days) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • max_profit([3,5,4,8,1,6]) → 7
  • max_profit([1,4,2,7]) → 6
  • max_profit([9,7,4,1]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Adding up every price rise breaks the rest-day rule, and selling early can block a better buy. Instead, describe how each day ends: holding a share, just sold, or free to buy.

Hint 2

Keep the best cash for each of the three states. Holding: keep the share, or buy from free. Sold: sell the share you held. Free: stay free, or rest after yesterday's sale.

Solution and why it works
pythonO(n) · O(1)
def max_profit(prices: list[int]) -> int:
    hold = float("-inf")                 # best cash while owning a share (none is owned before day 0)
    sold = free = 0                      # sold: sold that same day; free: may buy the next day
    for p in prices:
        # buying needs yesterday's `free`, never yesterday's `sold`: that is the rest day
        hold, sold, free = max(hold, free - p), hold + p, max(free, sold)
    return max(sold, free)

Each day depends only on the best cash in three states at the end of the day before, so three numbers replace a table: O(n) time, O(1) space. Buying is only allowed from free, which never sold the day before: that is how the rest day is enforced. The trap is the no-rest answer, adding up every rise: it gives 11 on the first example, where 7 is the best valid plan. Trying every buy day for each sale also works, but takes O(n²).

Related lab: Big-O growth