leetcode NO.121 买卖股票的最佳时机 白痴讲解 腾讯精选练习50

本文介绍了一种用于计算股票买卖最大利润的算法。通过一次遍历价格数组,算法能够找到买入和卖出的最佳时机,从而获得最大利润。文章对比了暴力解法和优化后的解法,指出暴力解法在大数据集上会超时。

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

在这里插入图片描述
DP
在这里插入图片描述

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

暴力法会超时

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值