> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/bu-chong-2140-dao/121.-best-time-to-buy-and-sell-stock.md).

# 121. Best Time to Buy and Sell Stock

\# Easy

{% hint style="info" %}
折线题，minpeak and maxpeak

暴力解题一定会超时

记录maxprofit，和minpeak

很有意义的一道关于折线的基础题
{% endhint %}

![](https://3288217904-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LxJcc9A1TOyn5a5HJQ4%2F-MHyPymsYQDAsHxrp0rV%2F-MHyf-gTcZY--Zx9eAKN%2F1600926757082.jpg?alt=media\&token=e0165444-0534-490b-82a2-086267815880)

### Solution:

1. if prices\[i]\<minpeak, 找到了当前最小值
2. if prices\[i] 不是最小值，计算profit，看能否获得最大盈利

```python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # edge case
        if len(prices) == 0:
            return 0
        
        maxprofit = 0
        minpeak = prices[0]
        for i in range(len(prices)):
            if prices[i] < minpeak:
                minpeak = prices[i]
            elif prices[i] - minpeak > maxprofit:
                maxprofit = prices[i] - minpeak
                    
        return maxprofit
```

Time complexity = $$O(n)$$ , space complexity = $$O(1)$$&#x20;
