[LeetCode]122. Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock II

题意:计算买入和卖出的最大收益,和1的区别在于,它可以进行多次交易,不过在买入新的之前需要把之前买入的给卖掉。

贪心算法

既然可以买卖多次,那么就不用维护一个数组去纪录最小值了,只要当天比前一天的收益要高,就卖出。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        res = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                res += prices[i] - prices[i-1]
        return res
posted @ 2017-08-29 03:42  banananana  阅读(138)  评论(0)    收藏  举报