---
# System prepended metadata

title: 'Week.4.EZ [121. Best Time to Buy and Sell Stock]'
tags: [leetcode]

---

---
image: https://leetcode.com/static/images/LeetCode_Sharing.png
tags: leetcode
---
# Week.4.EZ [121. Best Time to Buy and Sell Stock]
---
- 給一List, 找出最佳買賣日的獲利值
---
- 剛開始使用暴力法, 因為List會跑n^2次, 數值大就會Timeout
- 用雙指針的方法就很不錯, 只需跑一次紀錄, 也稱sliding window
---
```python!
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # 給一List, 找出最賺最多的買進賣出 
        
        # Brutal: 每日減去該日之前最小值,得結果 O(n^2)
        # res = [v-min(prices[:i+1]) for i,v in enumerate(prices)]
        # return max(res)
        # 果不其然 Time Limit Exceeded
        
        # 2pointer: l,r 
        l = r = res = 0
        n = len(prices)
        while r < n:
            profit = prices[r] - prices[l]
            print(profit)
            if profit < 0: # l最多停在r相同, 跌到區域新低就停
                l += 1
            else: # 只要正值就比較, 取最大
                res = max(res, profit)
                r += 1
        return res
```
[121. Best Time to Buy and Sell Stock]:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
