# **Leetcode筆記(Best Time to Buy and Sell Stock)**
:::info
:information_source: 題目 : Best Time to Buy and Sell Stock, 類型 : arrays , 等級 : easy
日期 : 2023/02/17,2023/04/29,2023/06/27,2023/09/12,2023/12/01,2025/02/21
:::
### 嘗試
沒有error,但皆為return 0
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
stock = {}
for key, price in enumerate(prices):
stock[price] = key
minKey, minPrice = min(zip(stock.keys(),stock.values()))
i = minKey
diff = 0
diffOld = 0
for i in stock:
diff = stock[i] - minPrice
if diff > diffOld:
diffOld = diff
return diffOld
return 0
```
2023/04/29
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
prev = prices[0]
max_price = 0
for i in range(1, len(prices)):
if prices[i] < prev:
prev = prices[i]
max_price = max(max_price, prices[i] - prev)
return max_price
# 嘗試用two pointer法再寫一次
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l ,r = 0, 1
max_price, max_temp = 0, 0
while r < len(prices):
# 右邊比較大(符合條件)
if prices[r] > prices[l]:
max_temp = prices[r] - prices[l]
max_price = max(max_price, max_temp)
# 右邊比較小(移動成新點)
else:
l = r
r += 1
return max_price
```
2023/06/27
sliding window,不斷找最小值,再去跟後面的算差額
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minBuy = prices[0]
diff = 0
for p in prices:
if p < minBuy:
minBuy = p
diff = max(diff, p - minBuy)
return diff
```
2023/09/12
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# two pointer
l, r = 0, 1
maxP = 0
while r < len(prices):
if prices[l] <= prices[r]:
maxP = max(maxP, prices[r] - prices[l])
else: # prices[r] < price[l]
l = r
r += 1
return maxP
```
2023/12/01
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1
maxRes = 0
while r < len(prices):
if prices[l] < prices[r]:
maxRes = max(prices[r] - prices[l], maxRes)
else:
l = r
r += 1
return maxRes
```
2025/02/21
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
minPrice = prices[0]
for p in prices:
if p < minPrice:
minPrice = p
else:
profit = max(profit, p - minPrice)
return profit
```
---
### **優化**
兩pointer法,空間複雜度O(1),因為沒用到額外記憶體,時間複雜度O(n),因為兩pointer最後會走完整個list
```python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1
maxmaxP = 0
while r < len(prices):
if prices[l] < prices[r]:
maxP = prices[r] - prices[l]
maxmaxP = max(maxP, maxmaxP)
else:
l = r
r = r + 1
return maxmaxP
```
---
**:warning: 錯誤語法**
:::warning
超過time limit可以檢查迴圈是否停止條件設錯
return會在跳出迴圈後回傳值
:::
**:thumbsup:學習**
:::success
while要自己加1,for不需要
如果在if內自己用也不用輸出的參數,則不用宣告在最外層
宣告可以合併一行l, r = 0, 1
可以maxmaxP = max(maxP, maxmaxP)
:::
**思路**

**講解連結**
https://www.youtube.com/watch?v=1pkOgXD63yU
Provided by. NeetCode
###### tags: `arrays` `easy` `leetcode`