Suppose we have stock price history, and we are allowed to buy only once and sell only once. The problem is to find the maximum profit we can make. Here is my code that I tested for basic test cases. I'm wondering if there are possible improvements for logic correctness.
My major idea is to keep record of in history minimal price, and determine if sell today (with the purchase of historical minimal price), whether we can make a larger profit.
prices = [100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97] result = 0 minSofar = prices for i in range(1, len(prices)): minSofar = min(minSofar, prices[i]) result = max (result, prices[i] - minSofar) print result