剑指Offer(Python多种思路实现):股票的最大利润

剑指Offer(Python多种思路实现):股票的最大利润

面试63题

题目:股票的最大利润

题:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可获得的最大利润是多少?例如,一只股票在某些时间节点的价格为{9,11,8,5,7,12,16,14}。

如果我们能在价格为5的时候买入并在价格为16时卖出,则能获得最大的利润为11.

解题思路:

class Solution():
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        min_price=float('inf')
        max_profit=0
        for price in prices:
            if price<min_price:
                min_price=price
            profit=price-min_price
            max_profit=max(max_profit,profit)
        return max_profit
发布了75 篇原创文章 · 获赞 7 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_44151089/article/details/104549458