1: def best_profit(prices):
2: n = len(prices)
3: best = 0
4: min_price = prices[0]
5: for i in range(n):
6: min_price = min(min_price, prices[i])
7: best = max(best, prices[i] - min_price)
8: return best
Line 1: define a function called best_profit. It expects an argument that is a list of prices
Line 2: let n store the values of the number of prices (days) received in the argument
Line 3: Let's assume the best profit is 0 (we can only get better than this)
Line 4: Let's assume the minimum price is the first one in the prices list
Line 5: Let's iterate through all the prices, as established before, we have n prices (days) in our list
Line 6: The minimum price (min_price) is either the old min_price, or the currently iterated price (price[i]), whichever is smaller.
Line 7: the best profit is the maximum of the best profit so far or the price difference between the currently iterated price and the minimum price (min_price) so far.
Line 8: return the best price.
Note: I do not believe this function works correctly though since the min_price changes throughout the loops and it may not have found the correct value yet when the best profit is calculated.
I've implemented my own solution for the problem and called in best_profit2. See the comparison of the two functions below:
import sys
def best_profit(prices):
n = len(prices)
best = 0
min_price = prices[0]
for i in range(n):
min_price = min(min_price, prices[i])
best = max(best, prices[i] - min_price)
return best
def best_profit2(prices):
min_price = sys.maxsize
max_price = 0
for price in prices:
if price < min_price:
min_price = price
if price > max_price:
max_price = price
return max_price - min_price
priceList = [2, 4, 6, 8, 9, 7, 5, 3, 1]
print(best_profit(priceList))
print(best_profit2(priceList))