买卖股票的最佳时机
给定一个数组,它的第i个元素是一支给定股票第i天的价格。如果你最多只允许完成一笔交易(即买入和卖出一只股票),设计一个算法来计算你所能获取的最大利润。在买入股票前不能卖出股票。
这个题目的思路就是,找出前i个数的最小值,然后用第j(j>i)个数减去最小值,进行比较。这里可以用python中自带的max()和min()函数来进行查找。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)==0:
return 0
min_prices=prices[0]
max_shouru=0
for i in range(len(prices)):
min_prices=min(min_prices,prices[i])
max_shouru=max(max_shouru,prices[i]-min_prices)
return max_shouru