好气哦,我这方法总是会有一个实例通过不了,就是特别长的那个实例,paste如下,欢迎大家找到错误并在留言评论~~~
My wrong code:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)==0 or len(prices)==1:
return 0
profit=0
for i in range(len(prices)-1):
for j in range(i+1,len(prices)):
if prices[j]>prices[i]:
profit=max([profit,prices[j]-prices[i]])
return profit
正确版本:
1.作者的思想肥肠巧妙,用到了两个肥肠有意义的概念!!!当前最小,当前最大!!!这种使用max(),min()函数实时更新的当前量可以减少循环层数,提高程序运行效率!!!
2.另外,有一点很有启发性,想获得当前最大,则可设初始值为0;想获得当前最小,可设初始值为正无穷,即float('inf').
Right Code:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit=0
min_price=float('inf')
for price in prices:
min_price=min(price,min_price)
max_profit=max(price-min_price,max_profit)
return max_profit