leetcode-easy-array-122 best time to buy and sell stocks II

mycode  69.45%

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

 

reference:

The following faster, fewer because the index to find some!

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

 

Guess you like

Origin www.cnblogs.com/rosyYY/p/10984842.html