所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# method one
# 考虑特殊情况空列表, 效率低
# return max([max(prices[i:])-prices[i] for i in range(len(prices))]) if prices else 0
# method two 还是效率低
# res = 0
# while prices:
# max_price = max(prices)
# tmp = max_price - min(prices[:prices.index(max_price)+1])
# if tmp < res:
# return res
# else:
# res = tmp
# prices.remove(max_price)
# return 0
# method three 时间复杂度 n ,空间复杂度1 ,不用冗余的max()操作
profit , min_price = 0 , float('inf')
for price in prices:
profit = max(price - min_price , profit)
min_price = min(price , min_price)
return profit
所有Leetcode题目不定期汇总在 Github, 欢迎大家批评指正,讨论交流。