Embercode
✕
Dynamic ProgrammingQuick quiz

State machine for stocks

8 questions. Covers Stock trading with k transactions and cooldown in Python.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``python def max_profit_cooldown(prices): hold = float('-inf') sold = float('-inf') rest = 0 for p in prices: new_hold = max(hold, rest - p) new_sold = hold + p new_rest = max(rest, sold) hold, sold, rest = new_hold, new_sold, new_rest return max(sold, rest) print(max_profit_cooldown([3, 1, 2, 5])) ``
  2. 2. What does this program print? ``python def max_profit_k(k, prices): buy = [float('-inf')] * (k + 1) sell = [0] * (k + 1) for p in prices: for j in range(1, k + 1): buy[j] = max(buy[j], sell[j - 1] - p) sell[j] = max(sell[j], buy[j] + p) return max(sell) print(max_profit_k(2, [2, 4, 1, 6])) ``
  3. 3. In the cooldown-only method, why does the buy line use rest - p and not max(rest, sold) - p?
  4. 4. Why is the final answer max(sold, rest) and never hold?
  5. 5. This version is meant to block a buy on the day after a sale. What does it print for the prices [1, 2, 3, 0, 2]? ``python def max_profit_cooldown(prices): hold = float('-inf') sold = float('-inf') rest = 0 for p in prices: new_hold = max(hold, max(rest, sold) - p) new_sold = hold + p new_rest = max(rest, sold) hold, sold, rest = new_hold, new_sold, new_rest return max(sold, rest) print(max_profit_cooldown([1, 2, 3, 0, 2])) ``

5 question(s) left on this page.