Embercode
✕
Dynamic ProgrammingQuick quiz

State machine for stocks

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

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <algorithm> #include <iostream> int main() { const long long NEG = -(1LL << 60); long long hold = NEG, sold = NEG, rest = 0; for (long long p : {4, 1, 6}) { const long long newHold = std::max(hold, rest - p); const long long newSold = hold + p; const long long newRest = std::max(rest, sold); hold = newHold; sold = newSold; rest = newRest; } std::cout << std::max(rest, sold) << '\n'; } ``
  2. 2. The same code runs on the prices 1, 2, 3, 0, 2 with no limit and a one-day cooldown after each sale. What does it print? ``cpp const long long NEG = -(1LL << 60); long long hold = NEG, sold = NEG, rest = 0; for (long long p : {1, 2, 3, 0, 2}) { const long long newHold = std::max(hold, rest - p); const long long newSold = hold + p; const long long newRest = std::max(rest, sold); hold = newHold; sold = newSold; rest = newRest; } std::cout << std::max(rest, sold) << '\n'; ``
  3. 3. In the state machine for stocks, why can a buy not happen on the day right after a sale?
  4. 4. Why does the final answer use the rest and sold states, and not the hold state?
  5. 5. The loop over b below goes upward, from 0 to k. For the prices 1, 2, 3, 0, 2 with k = 3, the function that returns the best of rest and sold gives 4, but the correct answer is 3. What causes the wrong answer? ``cpp for (long long p : prices) { for (int b = 0; b <= k; ++b) { const long long oldHold = hold[b]; const long long oldSold = sold[b]; const long long oldRest = rest[b]; long long newHold = oldHold; if (b >= 1) newHold = std::max(newHold, rest[b - 1] - p); hold[b] = newHold; sold[b] = oldHold + p; rest[b] = std::max(oldRest, oldSold); } } ``

5 question(s) left on this page.