### Solution

The max profit of current state only relevent to the previous minimium price. So we can use one variable to record the previous minimium price and update the current max profit.

The state transfer function is:

## Buy and sell multiple times

### Solution

1. Mathemetical View

If we analyze the graph, we notice that the points of interest are the consecutive valleys and peaks. For example, in the above case, if we skip $peak_i$ and $vally_j$, trying to obtain more profit by considering points with more difference in heights, the net profit obtained will always be lesser than the one obtained by including them, Since:

Therefore, we can find all the preak and valley pairs and calculate the total Profit:

1. Dynamic Programming

At the end of the $i_{th}$ day, we maintain cash, the maximum profit we could have if we did not have a share of stock, and hold, the maximum profit we could have if we owned a share of stock.

The intution is the state of today is only relevent to the yesterday. The State of yesterday can be expressed as :

Therefore , we can use two variables cash, hold to represent the above two states. The state transfer functions are:

1. keep the same as day i-1, or sell from hold status at day i-1
2. keep the same as day i-1, or buy from cash status at day i-1

### Solution

1. Dynamic Programming

See explanation above.