美文网首页
Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

作者: 穿越那片海 | 来源:发表于2017-03-12 21:38 被阅读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
    

    相关文章

      网友评论

          本文标题:Best Time to Buy and Sell Stock

          本文链接:https://www.haomeiwen.com/subject/ukuxnttx.html