Given an array prices[] representing stock prices, find the maximum total profit that can be earned by buying and selling the stock any number of times.
Note: We can only sell a stock which we have bought earlier and we cannot hold multiple stocks on any day.
Examples:
Input: prices[] = [100, 180, 260, 310, 40, 535, 695] Output: 865 Explanation: Buy the stock on day 0 and sell it on day 3 = 310 - 100 = 210 and Buy the stock on day 4 and sell it on day 6 = 695 - 40 = 655 so the Maximum Profit is = 210 + 655 = 865.
Input: prices[] = [4, 2] Output: 0 Explanation: Stock prices keep decreasing, there is no chance to sell at a higher price after buying, so no profit can be made.
[Naive Approach] By Trying All Possibility - O(2n) Time and O(n) Space
The idea is to use recursion to simulate all choices of buying and selling. For each day, you can either skip it or buy on that day. If you buy at day i, then you try all possible selling days j > i where price[j] > price[i].
Output
865
[Better Approach] Using Local Minima and Maxima - O(n) Time and O(1) Space
The idea is to traverse the array from left to right and Find local minima (where price starts rising) and then a local maxima (where price stops rising). Compute the difference between two and add to the result.
Below is the implementation of the algorithm
Output
865
[Expected Approach] By Accumulating Profit - O(n) Time and O(1) Space
The idea is that profit only comes when prices rise. If the price goes up from one day to the next, we can think of it as buying yesterday and selling today. Instead of waiting for the exact bottom and top, we simply grab every small upward move. Adding these small gains together is the same as if we had bought at each valley and sold at each peak because every rise between them gets counted.