143-121. 买卖股票的最佳时机

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。(第一个我理解错了,然后看了以前代码,第二三个我跟根据官网改编的,最后的几个你猜啊)
class Solution(object):
    def maxProfit1(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        length = len(prices)
        if not prices or length < 2:
            return 0

        dp = [[0, 0] for i in range(length)]
        dp[0][1] = -prices[0]
        print(dp)

        for i in range(1, length):
            dp[i][0] = max(dp[i-1][1] + prices[i], dp[i-1][0])
            dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
        return dp[length-1][0]

    def maxProfit1(self, prices):
        length = len(prices)
        if not prices or length < 2:
            return 0

        ret = 0
        for i in range(length):
            for j in range(i + 1, length):
                ret = max(ret, prices[j] - prices[i])
        return ret

    def maxProfit2(self, prices):
        """
        maxProfit3我感觉他的第二种方式比较难理解所以改造一下
        把第一天和第二天的给跳过,假设第一天就是最低价格,最大价值就是第二天减去第一天,然后其他的在循环中进行
        """
        length = len(prices)
        if not prices or length < 2:
            return 0

        min_price = prices[0]
        max_profit = prices[1] - min_price
        for i in range(2, length + 1):
            min_price = min(prices[i - 1], min_price)
            max_profit = max(prices[i - 1] - min_price, max_profit)

        return max_profit

    def maxProfit3(self, prices) -> int:
        inf = int(1e9)
        minprice = inf
        maxprofit = 0
        for price in prices:
            maxprofit = max(price - minprice, maxprofit)
            minprice = min(price, minprice)
        return maxprofit

    def maxProfit(self, prices):
        if prices == []:
            return 0
        small = prices[0]
        res = 0
        for x in prices:
            if x > small+res:
                res = x-small
                continue
            if x < small:
                small = x
                continue
        return res

if __name__ == '__main__':
    s = Solution()
    prices = [7, 1, 5, 3, 6, 4]
    prices = [7, 1]

    print(s.maxProfit(prices))
原文地址:https://www.cnblogs.com/liuzhanghao/p/14282516.html