LeetCode122买卖股票的最佳时机 II

LeetCode122买卖股票的最佳时机 II

未经博主同意,禁止瞎JB转载。

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/description/

我的解法:

对list中的元素作一阶差分,然后本题目就转换为求差分后的序列中非零元素的和。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        n = len(prices)
        if n < 2:
            return 0
        diff = [prices[i+1] - prices[i] for i in range(n-1)]
        ret = 0
        for j in diff:
            maxer = max(0,j)
            ret = ret + maxer
        return ret
            

 

posted @ 2018-10-24 21:06  嬴政有条北冥的鱼  阅读(128)  评论(0编辑  收藏  举报