leetcode 121. Best Time to Buy and Sell Stock 买卖股票的最佳时机 动态规划
leetcode 2020年3月 每日一题打卡
题目:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
思路: python动态规划:前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}。
刚开始看着道题,觉得很简单两层循环就够了,然后超时,我才发现我怎么这么天真。要善于发现解法中的动规思想啊!最可怕的是,我竟然都没有想到这道题用动规。
超时的代码:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
best=0
for i in range(0,len(prices)):
for j in range(i+1,len(prices)):
mon=prices[j]-prices[i]
if mon>0 and mon>best:
best=mon
return best
细节:
- 求list里的最小元素:a=min(list)
- list1[:i]:表示list里的元素是0,1,2…,i-1
动态规划的代码:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# 动态规划:前i天的最大收益 = max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
max_i=0
for i in range(1,len(prices)):
max_i=max(max_i,prices[i]-min(prices[:i]))
return max_i
本博客为原创作品,欢迎指导,转载请说明出处,附上本文链接,谢谢!