|
1 |
| -# 121. Best Time to Buy and Sell Stock |
2 |
| - |
3 |
| -**Difficulty:** Easy |
4 |
| -**Link:** https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ |
5 |
| - |
6 |
| -## Problem Description |
7 |
| - |
8 | 1 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `i^th` day.
|
9 | 2 |
|
10 | 3 | You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
|
11 | 4 |
|
12 | 5 | Return *the maximum profit you can achieve from this transaction*. If you cannot achieve any profit, return `0`.
|
13 | 6 |
|
14 | 7 | **Example 1:**
|
15 |
| -``` |
| 8 | +```text |
16 | 9 | Input: prices = [7,1,5,3,6,4]
|
17 | 10 | Output: 5
|
18 | 11 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
|
19 | 12 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
|
20 | 13 | ```
|
21 | 14 |
|
22 | 15 | **Example 2:**
|
23 |
| -``` |
| 16 | +```text |
24 | 17 | Input: prices = [7,6,4,3,1]
|
25 | 18 | Output: 0
|
26 | 19 | Explanation: In this case, no transactions are done and the max profit = 0.
|
@@ -68,7 +61,7 @@ For each price starting from the second:
|
68 | 61 | **Example walkthrough:**
|
69 | 62 | Let's trace through the first example:
|
70 | 63 |
|
71 |
| -``` |
| 64 | +```text |
72 | 65 | prices = [7,1,5,3,6,4]
|
73 | 66 |
|
74 | 67 | Initial state:
|
@@ -104,31 +97,5 @@ Result: Return max_profit = 5
|
104 | 97 |
|
105 | 98 | > **Note:** The key insight is that we don't need to try every possible buy-sell combination. By tracking the minimum price seen so far, we can calculate the maximum possible profit at each step in O(1) time.
|
106 | 99 |
|
107 |
| -### Solution |
108 |
| - |
109 |
| -```python |
110 |
| -class Solution: |
111 |
| - def maxProfit(self, prices: List[int]) -> int: |
112 |
| - # Handle edge case |
113 |
| - if not prices: |
114 |
| - return 0 |
115 |
| - |
116 |
| - # Initialize variables |
117 |
| - min_price = prices[0] |
118 |
| - max_profit = 0 |
119 |
| - |
120 |
| - # Iterate through the array starting from the second element |
121 |
| - for price in prices[1:]: |
122 |
| - # Update minimum price if current price is lower |
123 |
| - min_price = min(min_price, price) |
124 |
| - |
125 |
| - # Calculate potential profit and update maximum profit |
126 |
| - potential_profit = price - min_price |
127 |
| - max_profit = max(max_profit, potential_profit) |
128 |
| - |
129 |
| - # Return the maximum profit |
130 |
| - return max_profit |
131 |
| -``` |
132 |
| - |
133 | 100 | **Time Complexity:** O(n) - we visit each element exactly once
|
134 | 101 | **Space Complexity:** O(1) - we only use a constant amount of extra space
|
0 commit comments