|
| 1 | +""" |
| 2 | +Given a list of stock prices calculate the maximum profit that can be made from a |
| 3 | +single buy and sell of one share of stock. We only allowed to complete one buy |
| 4 | +transaction and one sell transaction but must buy before we sell. |
| 5 | +
|
| 6 | +Example : prices = [7, 1, 5, 3, 6, 4] |
| 7 | +max_profit will return 5 - which is by buying at price 1 and selling at price 6. |
| 8 | +
|
| 9 | +This problem can be solved using the concept of "GREEDY ALGORITHM". |
| 10 | +
|
| 11 | +We iterate over the price array once, keeping track of the lowest price point |
| 12 | +(buy) and the maximum profit we can get at each point. The greedy choice at each point |
| 13 | +is to either buy at the current price if it's less than our current buying price, or |
| 14 | +sell at the current price if the profit is more than our current maximum profit. |
| 15 | +""" |
| 16 | + |
| 17 | + |
| 18 | +def max_profit(prices: list[int]) -> int: |
| 19 | + """ |
| 20 | + >>> max_profit([7, 1, 5, 3, 6, 4]) |
| 21 | + 5 |
| 22 | + >>> max_profit([7, 6, 4, 3, 1]) |
| 23 | + 0 |
| 24 | + """ |
| 25 | + if not prices: |
| 26 | + return 0 |
| 27 | + |
| 28 | + min_price = prices[0] |
| 29 | + max_profit: int = 0 |
| 30 | + |
| 31 | + for price in prices: |
| 32 | + min_price = min(price, min_price) |
| 33 | + max_profit = max(price - min_price, max_profit) |
| 34 | + |
| 35 | + return max_profit |
| 36 | + |
| 37 | + |
| 38 | +if __name__ == "__main__": |
| 39 | + import doctest |
| 40 | + |
| 41 | + doctest.testmod() |
| 42 | + print(max_profit([7, 1, 5, 3, 6, 4])) |
0 commit comments