class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxProfit, minPrice= 0, float('inf')
for price in prices:
minPrice = min(minPrice, price)
maxProfit = max(maxProfit, price-minPrice)
return maxProfit
1 此题注意float('inf')的使用,正无穷,float('inf')负无穷,当要和元素比小的时候,可以初始化为float('inf');如果需要和元素比最大的时候,可以初始化为负无穷float('-inf')
2 此题解题思路:要找到最低的价格买入,然后再一一和当前值想减,看是不是maxprofit
Best Time to Buy and Sell Stock II
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
return sum(max(prices[i+1]-prices[i],0) for i in range(len(prices)-1))
解题思路:只要第二天的价格比前一天高,就买了再卖