[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

我们可以发现,dp数组只用到了上一个值,因此,直接维护一个变量就可以了。

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
posted @ 2017-08-29 03:23  banananana  阅读(99)  评论(0)    收藏  举报