--- title: leetcode-121 date: 2020-03-17 18:06:45 tags: categories: leetcode --- ### 121. 买卖股票的最佳时机 [题目](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/) 原始答案: ```python class Solution: def maxProfit(self, prices) -> int: profit = 0 if not prices: return profit min_buyin = prices[0] max_sellout = prices[0] l = len(prices) i = 0 for buyin in prices: if i == l: return profit if min_buyin <= buyin: max_sellout = max(prices[i:]) p = max_sellout - min_buyin if p > profit: profit = p if buyin < min_buyin: min_buyin = buyin i += 1 return profit #1880 ms 14.4 MB ``` 主要思路是找到波谷,如果当前价格比前一天要低,则还是在去往波谷的路上;当价格比前一天高或相同时,则到达了一个波谷,计算波谷和之后的波峰的差,就是这一段的利润。将从头至尾过一次,就能找到所有波谷和其后波峰的差,返回最大的即可。但是这个明显地在重复max,时间复杂度是O(n^2),看起来就很傻逼。 仔细想想,其实并不需要直接找出波谷后的波峰,只要在for loop时保持波谷为最低的那个,就能算出每一个后续与波谷的差,找最大差即可。改了下代码变成这样 ```python class Solution: def maxProfit(self, prices) -> int: profit = 0 if not prices: return profit min_buyin = prices[0] for i in range(1, len(prices)): min_buyin = min(min_buyin, prices[i-1]) profit = max(prices[i] - min_buyin, profit) return profit #44 ms 14.4 MB ```