直接实现,min,profit
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices oor len(prices) < 2: return 0 min_price = prices[0] profit = 0 for price in prices: min_price = min(min_price, price) profit = max(profit, price - min_price) return profit
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices oor len(prices) < 2: return 0 profit = 0 for i in range(1, len(prices)): if prices[i] > prices[i - 1]: profit += prices[i] - prices[i - 1] return profit
123. 买卖股票的最佳时机 III
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ buy1 = buy2 = float('-inf') sell1 = sell2 = 0 # 把四个值都理解为手上省的钱,每次手上都要剩最多的钱 for price in prices: sell2 = max(sell2, buy2 + price) # sell2 就是第二次卖了手上剩的钱 buy2 = max(buy2, sell1 - price) # 第二次买就就是第一次卖的钱-价格=手上剩的钱 sell1 = max(sell1, buy1 + price) # 第一次卖取buy1+price和sell1的最大值 buy1 = max(buy1, -price) # 第一次买是花钱的,取 -price 和 buy1的最大值,buy1是负值 return sell2