Leetcode122. Best Time to Buy and Sell Stock II Python实现

题目
这题比着上题稍微复杂了一点。
因为不止可以买卖一次,可以买卖多次。
其实也不难,比如:
[1,2,3,4,5] 结果应该是4 ,5-1,这个肯定不好操作啊,因为要一直往后找,其实也可以这样操作:(2-1)+(3-2)+(4-3)+(5-4)=4。
题中没有约束一天不能卖出再买入,所以可以利用这个来化简代码:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices)<1:
            return 0
        
        ans = 0
        for i in range(1,len(prices)):
            if prices[i]>prices[i-1]:
                ans+=prices[i]-prices[i-1]
        return ans

Runtime: 44 ms, faster than 72.72% of Python3 online submissions for Best Time to Buy and Sell Stock II.
Memory Usage: 14 MB, less than 5.06% of Python3 online submissions for Best Time to Buy and Sell Stock II.
这样也算利用了贪心算法。

但是如果约束,同一天卖出了就不能再买入呢。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices)<1:
            return 0
        
        ans = 0
        i=0
        while i<len(prices)-1 and prices[i]>=prices[i+1]:
            i+=1
        while i<len(prices)-1:
            buy = i
            while i<len(prices)-1 and prices[i]<=prices[i+1]:
                i+=1
            ans+=prices[i]-prices[buy]
            i+=1

        return ans
``
Runtime: 64 ms, faster than 14.60% of Python3 online submissions for Best Time to Buy and Sell Stock II.
Memory Usage: 14.1 MB, less than 5.06% of Python3 online submissions for Best Time to Buy and Sell Stock II.
posted @ 2019-03-22 12:59  大胖子球花  阅读(92)  评论(0)    收藏  举报