Best Time to Buy and Sell Stock

2017-03-12  本文已影响0人  穿越那片海

Easy

给定一个序列,其第i个元素为某股票的第i天的股价。假如你可以做多笔买入和卖出的交易,确定你的最大收益。不能同时开多个仓位,在建立新仓位之前必须把之前开的仓位平掉。

有了股票买卖1的思路,此题更加简单,只要差值序列中出现正值就应当做出买卖。

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

猜你喜欢

热点阅读