Leetcode122、买卖股票的最佳时机II(Python题解)不限买卖次数,字节跳动面试题

本文探讨了LeetCode上的第122题,即在不限制买卖次数的情况下,如何在股票市场中获取最大利润。提供了贪心策略和寻找谷底、峰顶的方法作为解题思路,并以Python实现。适合准备面试和算法学习者阅读。

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

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

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

难度:简单

分析
本题提供两种解法
1、贪心。
只要后一天比前一天价格高就买卖。
2、谷底买入,峰顶卖出
用一个变量记录谷底,用一个flag判断是否持有股票。
解决方法
1
贪心

#贪心
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i - 1]:
                profit += prices[i] - prices[i - 1]
        return profit

2
谷底买入,峰顶卖出。

#谷底买入,峰顶卖出
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        flag=False##是否持有股票
        profit=0
        buy_point=0
        for i in range(len(prices)-1):
            if prices[i] > prices[i+1] and flag == False:##处于下降数列中,不买入
                continue
            elif prices[i] < prices[i+1] and flag == False:##记录谷底,买入
                buy_point = i
                flag = True
            if prices[i] < prices[i+1] and flag == True:##处于上升数列中,不卖出
                continue
            elif prices[i] > prices[i+1] and flag == True:##峰顶,卖出
                profit += prices[i] - prices[buy_point]
                flag = False
        if  flag == True:##如果在结束仍然持有股票,则在最后一天卖出(由于在下降数列中不会买入,此时必然是高于买入价的)
            profit += prices[-1] - prices[buy_point]
        return profit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值