This solution fails with the case [7,1,3,2,6,4]. Here this algorithm would return 6 because 7-1=6, however you have to buy the share before you can sell it so 7 is not a useable sale price. The correct answer should be 6-1=5, buy the share at 1 and sell at 6.
Because the problems later are relied on the problems before, such as we use MIN(i) to represent the lowest
price before the ith day, and MAX(i) to represent the max profit before the ith day, so, for a string of length 6, when we consider the max profit of the whole process MAX(5), we found that it relied on all the days before it, so MIN(5) = min(prices, MIN(5)), MAX(5) = max(prices - MIN(5), MAX(4)).