【剑指 Offer】剑指 Offer 63. 股票的最大利润

这篇博客探讨了三种不同的Python代码实现来求解股票最大利润问题。方法1使用了简单的循环,方法2通过构建最高价格数组优化了时间复杂度,而方法3通过跟踪最低价格来减少计算。所有方法均通过了200个测试用例,并在执行时间和内存使用上有所不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
代码
执行用时:4532 ms, 在所有 Python3 提交中击败了5.03% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了29.51% 的用户
通过测试用例:200 / 200

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit=0
        for i in range(len(prices)):
            if i+1<len(prices):
                max_profit=max(max_profit,max(prices[i+1:])-prices[i])
        return max_profit

【方法2】
执行用时:52 ms, 在所有 Python3 提交中击败了17.09% 的用户
内存消耗:15.6 MB, 在所有 Python3 提交中击败了57.31% 的用户
通过测试用例:200 / 200

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        high=[prices[-1]]*len(prices)
        index=len(prices)-2
        while index>=0:
            high[index]=max(prices[index],high[index+1])
            index-=1
        ans=0
        for i in range(len(prices)-1):
            ans=max(ans,high[i+1]-prices[i])
        return ans

【方法3】
执行用时:40 ms, 在所有 Python3 提交中击败了65.62% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了39.41% 的用户
通过测试用例:200 / 200

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:return 0
        ans=0
        min_num=prices[0]
        for i in range(1,len(prices)):
            min_num=min(min_num,prices[i])
            ans=max(ans,prices[i]-min_num)
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值