|
24 | 24 | # Space Complexity: O(1) |
25 | 25 | # --------------------------------------------------------------- |
26 | 26 |
|
27 | | -def max_profit(prices): |
| 27 | +from typing import List |
| 28 | + |
| 29 | +def max_profit(prices: List[int]) -> int: |
28 | 30 | """ |
29 | | - Calculate maximum profit from at most one buy-sell transaction. |
| 31 | + Calculate the maximum profit from at most one buy-sell transaction. |
30 | 32 |
|
31 | 33 | Parameters: |
32 | | - prices (list[int]): List of stock prices per day. |
| 34 | + prices (List[int]): List of stock prices per day. |
33 | 35 |
|
34 | 36 | Returns: |
35 | 37 | int: Maximum profit possible. Returns 0 if no profit is possible. |
36 | | - """ |
37 | 38 |
|
38 | | - # Edge case: no transaction possible if list is too short |
| 39 | + Doctests: |
| 40 | + >>> max_profit([7, 10, 1, 3, 6, 9, 2]) |
| 41 | + 8 |
| 42 | + >>> max_profit([7, 6, 4, 3, 1]) |
| 43 | + 0 |
| 44 | + >>> max_profit([1, 3, 6, 9, 11]) |
| 45 | + 10 |
| 46 | + """ |
39 | 47 | if not prices or len(prices) < 2: |
40 | 48 | return 0 |
41 | 49 |
|
42 | | - # Initialize minimum price as the first day's price |
43 | 50 | min_price_so_far = prices[0] |
| 51 | + max_profit_val = 0 |
44 | 52 |
|
45 | | - # Initialize maximum profit |
46 | | - max_profit = 0 |
47 | | - |
48 | | - # Traverse price list starting from the second day |
49 | 53 | for price in prices[1:]: |
50 | | - # Update the minimum price seen so far |
51 | 54 | min_price_so_far = min(min_price_so_far, price) |
| 55 | + max_profit_val = max(max_profit_val, price - min_price_so_far) |
52 | 56 |
|
53 | | - # Calculate today's potential profit |
54 | | - profit_today = price - min_price_so_far |
55 | | - |
56 | | - # Update max profit if today's profit is higher |
57 | | - max_profit = max(max_profit, profit_today) |
| 57 | + return max_profit_val |
58 | 58 |
|
59 | | - return max_profit |
60 | 59 |
|
61 | 60 |
|
62 | 61 | # --------------------------------------------------------------- |
|
0 commit comments