I go through the EPI book and need help to understand this part.

There is one problem 5.7, which is to buy and sell twice in a single time series to maximize profits. The entry is made as a list of ints. The example they give is:

```
(12, 11, 13, 9, 12, 8, 14, 13, 15)
```

Here, the maximum profit of a single buy-sell event is 7; buy at 8 and sell at 15. At two buy-sell events, there are 10; buy at 9, sell at 12 and buy at 8, sell at 15.

The intuition for a single buy-sell is simple if we just track the minimal item in the list and the difference between the minimum and the current item is the profit.

What I do not understand is how the double buy-sell formula works. The book proposes a solution in which two passes through the data, one forward and one backward pass. The forward pass uses the same formula as above (single buy-sell), but the backward pass starts at the bottom of the list and tracks the maximum instead. The winnings of the reverse pass are stored in an array and added to the winnings of the forward pass $ M (i) = F (i-1) + B (i) $, and where $ F (-1) = 0 $,

Why does the backward pass follow the maximum and how does the formula ensure that we do not buy before the second sale?

Here is the solution code:

```
def buy_and_sell_stock_twice(prices: List(float)) -> float:
max_total_profit, min_price_so_far = 0.0, float('inf')
first_buy_sell_profits = (0.0) * len(prices)
for i, price in enumerate(prices):
min_price_so_far = min(min_price_so_far, price)
max_total_profit = max(max_total_profit, price - min_price_so_far)
first_buy_sell_profits(i) = max_total_profit
# Now for the backwards pass.
max_price_so_far = float('-inf')
for i, price in reversed(list(enumerate(prices(1:), 1))):
max_price_so_far = max(max_price_so_far, price)
max_total_profit = max(
max_total_profit,
max_price_so_far - price + first_buy_sell_profits(i - 1))
return max_total_profit
```

For some reason, the code highlighting does not appear in the design even though I've specified the language.

I have broken down the iterator in reverse, resulting in:

```
((8, 15), (7, 13), (6, 14), (5, 8), (4, 12), (3, 9), (2, 13), (1, 11))
```

The expected result of the backward pass is also provided for the sample data:

```
B = (7, 7, 7, 7, 7, 7, 2, 2, 0)
```

Through the code I can see how the algorithm can be used to fill B. What makes no sense is why this backward pass guarantees the maximum profit, how it guarantees sensible purchases and sales, and what the intuition is for the way.

I looked at similar questions, but they provide different solutions that work well but do not give insight into the book's solution. The book is not readily available online, so there is less content about the material.