This problem is similar to Best Time to Buy and Sell Stock. Given `prices`

, we find the day (denoted as `buy`

) of the first local minimum and the day (denoted as `sell`

) of the first local maximum (note that we initialize `sell`

to be `buy + 1`

each time to guarantee the transaction is valid). Then we earn the profit `prices[sell] - prices[buy]`

, after which we update `buy`

to be `sell + 1`

to check for the remaining `prices`

.

The code is as follows.

```
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy = 0, sell = 0, profit = 0, n = prices.size();
while (buy < n && sell < n) {
while (buy + 1 < n && prices[buy + 1] < prices[buy])
buy++;
sell = buy;
while (sell + 1 < n && prices[sell + 1] > prices[sell])
sell++;
profit += prices[sell] - prices[buy];
buy = sell + 1;
}
return profit;
}
};
```