LeetCodeWithPython 122. 买卖股票的最佳时机 II

博客围绕LeetCode上股票买卖问题展开,给出题目链接https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/ ,介绍了峰谷法解题思路,参考官方思路,强调要考虑连续峰和谷,紧跟谷的每个峰值以最大化利润。使用Python语言求解。

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

题目链接

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

题目描述

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

代码初步

  • 方法1: 峰谷法
    参考leetcode官方给出的思路
  • 算法
    假设给定的数组为:
    [7, 1, 5, 3, 6, 4]
    如果我们在图表上绘制给定数组中的数字,我们将会得到:
    在这里插入图片描述
    我们的兴趣点落在连续的峰和谷上。关键是我们需要考虑到紧跟谷的每一个峰值以最大化利润。如果我们试图跳过其中一个峰值来获取更多利润,那么我们最终将失去其中一笔交易中获得的利润,从而导致总利润的降低。因为C的长度是不可能大于A+B的

代码欣赏

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        maxprofit = 0
        if len(prices)<1:
            return maxprofit
        valley=prices[0]
        i=1
        peak=prices[0]
        while i<len(prices):
            # 查找谷底的值:谷底的特征就是后一个数B大于前一个数A,则A为谷底
            while i<len(prices) and (prices[i]<=prices[i-1]):
                i=i+1
            valley = prices[i-1]
            # 查找谷峰的值:谷峰的特征就是后一个数B小于前一个数A,则A为谷底
            while i<len(prices) and (prices[i]>=prices[i-1]):
                i=i+1
            peak = prices[i-1]
            maxprofit += peak-valley
        return maxprofit

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值