Mathematical expression for the quantity that we are maximising in the stock buying and selling problem
To write the profit as a mathematical expression, you need to set up a little more notation for the buys and sells. Let $x[1], \ldots, x[n]$ be the stock prices on days $1, \ldots, n$. For each buy and sell, let $b$ denote the day on which the stock is bought, and $s$ the day on which it is sold. The problem says that we must have $1 \leq b &lt; s \leq n$. The profit from this single transaction is $P = x[s] - x[b]$.
However, the problem allows many buys and sells, say $(b_1, s_1), \ldots, (b_k, s_k)$ for some numbers which must satisfy $$1 \leq b_1 &lt; s_1 &lt; b_2 &lt; s_2 &lt; \cdots &lt; b_k &lt; s_k \leq n.$$
The total profit from these $k$ transactions is
$$ P = \sum_{i = 1}^k \left(x[b_i] - x[s_i]\right). $$
Of course the tricky part is that you don't know ahead of time what $k$ should be, so you're not only trying to optimise over the $b_i$ and $s_i$ variables, but also $k$.