您的位置:首页 > 其它

【Leetcode】Best Time to Buy and Sell Stock

2015-09-20 15:17 281 查看

1 题目



2 Python代码

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
low = prices[0]
ans = 0
for i in  range(len(prices)):
if prices[i] < low:
low = prices[i]
elif (prices[i] - low) > ans:
ans = prices[i] - low

return ans


3 分析

正解:从前向后遍历,遍历过程中对最小值和与最小值所得的最大差进行更新,最后返回最大差;时间复杂度为O(n)

误解: 一开始,考虑对每一个数,计算其后面所有数中的最大值,然后用这个最大值减去该数得到该数所对应的最大差;最后返回这些最大差中的最大值;但时间复杂度为O(n^2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: