[LeetCode]121. Best Time to Buy and Sell Stock
121. Best Time to Buy and Sell Stock
动态规划
dp[0] = prices[0]
dp[i] = prices[i] (if prices[i] < dp[i-1])
dp[i] = dp[i-1] (if prices[i] > dp[i-1])class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        dp = [0] * len(prices)
        max_profit = -1e9
        for i in range(0, len(prices)):
            if i == 0:
                dp[i] = prices[i]
            else:
                if prices[i] > dp[i-1]:
                    dp[i] = dp[i-1]
                else:
                    dp[i] = prices[i]
            max_profit = max(max_profit, prices[i]-dp[i])
        return max_profit
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        mi, ma = 1e9, -1e9
        for i in range(0, len(prices)):
            mi = min(mi, prices[i])
            ma = max(ma, prices[i]-mi)
        return ma 
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号