数组_02_买卖股票的最佳时机_II

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        解题思路:其实就是找到斜向上的这个点(↗️),当前节点 prices[cur] < prices[cur+1] cur就是买入的点。
        向下走,直到到达这次买入的最高点卖出,即 prices[cur(n)] > prices[cur(n+1)] 结束
        """
        cur = 0
        money = 0
        length = len(prices)
        while cur < length - 1:
            if prices[cur] < prices[cur + 1]:
                buy = prices[cur]
            else:
                cur += 1
                continue
            while prices[cur] < prices[cur + 1]:
                cur += 1
                # 下面这句肯定是在最后一个交易周期里执行
                if cur >= length - 1:
                    break
            sal = prices[cur]
            money += (sal - buy)

        return money


# leetcode 上的最优解 其实不用等到最高点再卖出,只要下一个比当前值高,就可以卖出。
class Solution2(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        profit = 0
        for i in range(1, len(prices)):
            tmp = prices[i] - prices[i - 1]
            if tmp > 0:
                profit += tmp
        return profit


s = Solution()
# prices = [7, 1, 5, 3, 6, 4]
# prices = [1, 2, 3, 4, 5]
prices = [7, 6, 4, 3, 1]
print(s.maxProfit(prices))

你可能感兴趣的:(数组_02_买卖股票的最佳时机_II)