Best Time to Buy and Sell Stock I股票买卖1

Easy

给定一个序列,其第i个元素为某股票的第i天的股价。假如你只能做一笔买入和卖出的交易,确定你的最大收益。

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大收益为6-1=5,不是7-1=6,先买后卖。

Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
这种情况下不做交易,收益为0

此题其实是子序列最大和问题的变种,我们只需要将序列转化为差值序列,然后求差值序列的最大和就可以了。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        
        localmax, globalmax = 0, 0  
        
        if len(prices) > 1:
            prices_diff = [prices[i+1]-prices[i] for i in range(len(prices)-1)]
            for p in prices_diff:
                globalmax = max(globalmax, localmax+p)
                localmax = max(0, localmax+p)
        return globalmax   

你可能感兴趣的:(Best Time to Buy and Sell Stock I股票买卖1)