剑指offer系列-面试题63. 股票的最大利润(python)

1. 题目

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

2. 解题思路

详情见 面试题63. 股票的最大利润(动态规划,清晰图解)

当前的最大利润 = max(之前的最大利润, 当前price-之前的最小值)

3. 代码实现

3.1

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        """
        1. 动态规划,有些类似于最大子数组和这类问题
            1)记录之前的最大利润;2)记录之前的最小值位置
        """
        lirun = 0 # 记录最大利润
        min_index = 0 # 记录之前的最小值下标

        for i in range(1, len(prices)):
            temp = prices[i] - prices[min_index]
            if temp < 0: min_index = i # 更新最小值下标
            if temp > lirun:
                lirun = temp # 更新最大利润
            

        return lirun

3.2 优化

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        cost, profit = float("+inf"), 0
        for price in prices:
            cost = min(cost, price)
            profit = max(profit, price - cost)
        return profit

作者:jyd
链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/solution/mian-shi-ti-63-gu-piao-de-zui-da-li-run-dong-tai-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

4. 总结

5. 参考文献

[1] 剑指offer丛书
[2] 剑指Offer——名企面试官精讲典型编程题

猜你喜欢

转载自blog.csdn.net/besmarterbestronger/article/details/106480714
今日推荐