I was asked this problem in a interview:
Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to buy one share of the stock and sell one share of the stock, design an algorithm to find the best times to buy and sell. I was able to give an O(n) algorithm.
While the interviewer asked me a followed on question, what is the case with “buy one, sell one”, and then “buy one, sell one”, which means there are two trades in one day, maximize the profit. I was able to give an O(n^2) algorithm. But the interviewer said it can be improved. Is there a O(n) algorithm?
The interviewer said that you can not buy two share at the same time. You must buy one sell it, and then buy one at another time, then sell it.
The O(n) solution given in the original question’s reference gives the optimal “buy one then sell one” answer for each prefix of the original array. That algorithm could also be trivially modified to cope with the “backwards” situation; i.e. a “sell one then buy one” where you are working backwards from the array; that’s equivalent to having the “buy one then sell one” answer for each suffix of the array.
Now, in the “buy, sell, buy, sell” case we have some point (after the first sell) where we are somewhere within our array, say b. For that breakpoint the best solution would be the best prefix solution for 0..b and the best suffix solution for b+1..n. The best “buy, sell, buy, sell” overall is the optimum of these optimum solutions.
So, to solve the “buy, sell, buy, sell” in O(n), you can solve the prefix in O(n), suffix in O(n), and then for each breakpoint calculate the optimum – so nO(1). That’s an O(n) algorithm using O(n) space.