题目
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
示例
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6 - 1 = 5 。
注意利润不能是 7 - 1 = 6, 因为卖出价格需要大于买入价格。
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
解法
动态规划 (Python)
class Solution:
def maxProfit(self, prices) -> int:
if(len(prices) <= 0):
return 0
left = prices[0]
profit = 0
for i in range(1, len(prices)):
if((prices[i] - left) > profit):
profit = prices[i] - left
left = min(prices[i], left)
return profit
基本思路
一开始看没什么头绪,感觉和动态规划没什么关系。但想一下动态规划原问题和子问题之间的关系,可以发现,第i
天的股票最大收益f(i) = max(f(i - 1), p[i] - min(p[0:i]))
,其中p[i]
表示第i
天的股票价格,p[0:i]
表示前i - 1
天的股票价格。这里的left
记录的是前i - 1
天最低的股票价格,profit
记录的是前i - 1
天的最大收益。
复杂度分析
因为只遍历了一次prices
,所以时间复杂度为O(N)O(N)O(N)。空间上使用了left
和profit
,所以复杂度为O(1)O(1)O(1)。
优化
- 一直不太清楚把a和b中较大者赋值给b,用
if
语句比较快,还是min
比较快,看起来min
更简洁。但在执行了一百万次后,我发现在只有两个数时,min
耗时是if
的三倍多。 len(prices) == 0
比prices == []
慢一半左右。- 如果
left
比prices[i]
大,是不需要比较prices[i] - left
和profit
的。
class Solution:
def maxProfit(self, prices) -> int:
if(prices == []):
return 0
left = prices[0]
profit = 0
for i in range(1, len(prices)):
if(left > prices[i]):
left = prices[i]
elif((prices[i] - left) > profit):
profit = prices[i] - left
return profit