1.买卖股票的最佳时机https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

拿到这题首先想到最暴力的方法,遍历

1 class Solution:
2     def maxProfit(self, prices: List[int]) -> int:
3         max_profit = 0
4         for i in range(len(prices) - 1):
5             for j in range(1, len(prices) - i):
6                 max_profit = prices[i+j] - prices[i] if prices[i+j] - prices[i] > max_profit else max_profit
7         return max_profit

但是超出时间限制了

看到了官方的“历史最低点”方法,仔细思考了一下确实很有道理,只需要遍历一次,思想类似于动态规划。

1 class Solution:
2     def maxProfit(self, prices: List[int]) -> int:
3         inf = int(1e9)
4         minprice = inf
5         maxprofit = 0
6         for price in prices:
7             maxprofit = max(price - minprice, maxprofit)
8             minprice = min(price, minprice)
9         return maxprofit

 

2.买卖股票的最佳时机 IIhttps://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

这一题感觉比上一题更简单,只要后一天比第一天涨了就可以将差值加到结果里面。相当于贪心算法

1 class Solution:
2     def maxProfit(self, prices: List[int]) -> int:
3         max_profit = 0
4         for i in range(len(prices) - 1):
5             max_profit += prices[i+1] - prices[i] if prices[i+1] - prices[i] > 0 else 0
6         return max_profit

执行用时超越99.41%

 

3.

 

posted on 2021-01-21 17:35  zmbreathing  阅读(124)  评论(0编辑  收藏  举报