121. Best Time to Buy and Sell Stock
## description
## 121. Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day.
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.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
1Input: prices = [7,1,5,3,6,4]
2Output: 5
3Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
4Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.Example 2:
1Input: prices = [7,6,4,3,1]
2Output: 0
3Explanation: In this case, no transactions are done and the max profit = 0.- –1 <= prices.length <= 105
- –0 <= prices[i] <= 104
Constraints:
## notes
### Intuition
Since we must buy before we sell, we want to find the lowest price followed by the highest price after it. When we encounter a new low, that becomes our new potential buy point since any future profit would be better calculated from this lower price.
### Implementation
Use two pointers: buy starting at index 0 and sell at index 1. Iterate while sell is in bounds. Calculate the current profit—if positive, update the max profit. If the profit is negative or zero, we've found a lower price, so move buy to the current sell position. Always increment sell to continue scanning forward.
### Edge-cases
If the array has fewer than 2 elements, no transaction is possible, so return 0 immediately.
- –Time: O(n) — single pass through the array
- –Space: O(1) — only tracking pointers and max profit
### Complexity
## solution
1from typing import List
2
3class Solution:
4 def maxProfit(self, prices: List[int]) -> int:
5 if len(prices) <= 1:
6 return 0
7 max_p = 0
8 b, s = 0, 1
9 while s < len(prices):
10 profit = prices[s] - prices[b]
11 if profit > 0:
12 max_p = max(max_p, profit)
13 else:
14 b = s
15 s += 1
16 return max_p
17
18
19
20
21if __name__ == "__main__":
22 # Include one-off tests here or debugging logic that can be run by running this file
23 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
24 solution = Solution()
25