Leetcode练习(Python):数组类:第121题:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 注意:你不能在买入股票前卖出股票。

题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。  如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。  注意:你不能在买入股票前卖出股票。
思路:动态规划(最佳),还可以用暴力
在某教育科技公司面试时遇到过。
程序1:动态规划
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length <= 1:
            return 0
        buy = prices[0]
        auxiliary = [0] * length
        for index in range(1, length):
            auxiliary[index] = max(auxiliary[index - 1], prices[index] - buy)
            buy = min(buy, prices[index])
        result = max(auxiliary)
        return result
程序2:暴力
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length <= 1:
            return 0
        if length == 2:
            if prices[0] >= prices[1]:
                return 0
            else:
                return prices[1] - prices[0]
        #Find the buy point
        index1 = 1
        auxiliary_buy = []
        auxiliary_buy.append(prices[1])
        auxiliary_sell = []
        auxiliary_sell.append(prices[length - 1])
        while index1 < length:
            if prices[index1] < prices[index1 - 1]:
                auxiliary_buy.append(prices[index1])
                buy = min(auxiliary_buy)
                #Find the sell point
                auxiliary_sell.append(max(prices[index1 : ]))
                sell = max(auxiliary_sell)
                result = sell - buy 
                if result <= 0:
                    return 0
                    break
            index1 += 1
        return result
            

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12743136.html