[LeetCode] 122. 买卖股票的最佳时机ii best-time-to-buy-and-sell-stock-ii(贪心算法)

思路:

只要第二天的价格高于第一天,就进行交易。(这样的话就默认可以同一天内先卖出再买进)

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        profit=0
        for i in range(0,len(prices)-1):
            temp=prices[i+1]-prices[i]
            if temp>0:
                profit += temp
        return profit

复杂度分析:

  • 时间复杂度:O(n),遍历一次。
  • 空间复杂度:O(1),需要额外的常量空间。

不过这种方法虽然简单,但只有遍历,感觉没有用到贪心的精髓,毕竟实际上不可能提前就知道第二天的股票价格。

猜你喜欢

转载自www.cnblogs.com/nicetoseeyou/p/10403614.html