LeetCode 121.买卖股票的最佳时机(一)
2019-10-15 13:51
183 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dddduaua/article/details/102565540
LeetCode 121.买卖股票的最佳时机(一)
难度:简单
题目描述
思路求解
动态规划法求解,初始化一个表,保存每一天股票的涨跌,设为diff
其中diff[i] 表示第 i 天的股票与第 i-1 天的股票差价
初始化动态规划中保留子问题所用的表,设为dp
其中,dp[i] = max( 0, dp[i-1] + diff[i] )
然后记录最大的dp[i]
解释一下上面的最优子结构公式啊,这其实可以看成一个连续型的问题,但是我们不允许其中出现负值(即亏钱)。所以如果股票一直在涨,我们的收益便连续的涨,若某一天跌倒特别低了,我们不卖便是,相反由于股票价格低,我们考虑买入,然后再随着价格增长卖出。另外需要我们记录中间的差价。
代码求解
class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) < 2 : return 0 diff = [0] pmax = 0 for i in range(1,len(prices)): diff.append(prices[i]-prices[i-1]) dp = [0] for i in range(1,len(prices)): dp.append(max(0,dp[i-1]+diff[i])) pmax = max(pmax, dp[i]) return pmax
求解结果
欢迎关注公众号 : 数学算法实验室
相关文章推荐
- LeetCode || 121-124. 买卖股票的最佳时机
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- LeetCode刷题笔记121:买卖股票的最佳时机
- C++Leetcode121:买卖股票的最佳时机
- 【leetcode系列】121. 买卖股票的最佳时机
- leetcode-121-买卖股票的最佳时机
- Leetcode之121. 买卖股票的最佳时机
- 基础算法之买卖股票最佳时机(Leetcode-121)
- LeetCode 121 买卖股票的最佳时机 Python
- LeetCode-121.买卖股票的最佳时机(相关话题:动态规划)
- Leetcode121: 买卖股票的最佳时机
- Leetcode121 Best Time to Buy and Sell Stock(买卖股票的最佳时机1)
- LeetCode 121. 买卖股票的最佳时机
- leetCode-122.买卖股票的最佳时机Ⅱ
- LeetCode刷题指南:买卖股票的最佳时机II
- [leetcode] Python(2)--买卖股票的最佳时机 II(122)、旋转数组(189)
- LeetCode:买卖股票的最佳时机 IV
- Java&LeetCode 初入门——122. 买卖股票的最佳时机 II
- LeetCode 122. 买卖股票的最佳时机 II
- [Leetcode] Best time to buy and sell stock ii 买卖股票的最佳时机