blog/source/_posts/2020-03-17-leetcode-121.md
Ching 9690121403 feat(init project): add all existing files
add all existing files

Signed-off-by: Ching <loooching@gmail.com>
2022-02-02 19:04:18 +08:00

60 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
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/)
<!--more-->
原始答案:
```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
```