Here is an explanation why
Best time to buy and sell stocks II
This time, multiple transactions are allowed with an exception that these transactions must not overlap. meaning once you buy, you must sell before you can buy again.
Observations

If you buy on day i and sell it on day j, (i < j) you may not make the greatest profit during that time window, as there might be day k (i < k < j) where P[day k] > P[day j]. you need to sell earlier.

if you buy on day i and sell it on day j (i < j), you may not make the greatest profit POSSIBLE with that stock because there might be day k (i < k < j) where P[day k] > P[day j]. you are better off if you hold off and sell it on day k
Optimality is garunteed if we avoid the two suboptimal transactions mentioned above
Combining these two observations, we observe that this problem boils down to capturing all the positive differences between day[i] and day[i + 1] if and only if P[day i+1] > P[day i].
This avoids the mistake of observation 1 (because you would have sold on day k already)
and essentially cancels out unnecessary transactions in case of observation 2. If you buy on day i and if P[day i + 2 ] > P[day i + 1]. conditions are satisfied and you end up doing the following
total profit = (P[day i + 1]  P[day i]) + (P[day i + 2]  P[day i + 1]) = P[day i + 2]  P[day i], thus ensuring the maximum profit for the stock bought on day[i]
comment if you still have questions