122. Best Time to Buy and Sell Stock II

本文介绍了一种计算股票交易最大利润的算法。该算法允许进行多次买卖操作,但每次只能持有不超过一支股票。通过计算每日价格差额并累加所有正值来确定最大利润。

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

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
给出一个数组,数组里的第i个元素是股票在第i天的价格,同时最多只能持有一支股票,不可同天买进卖出,返回最大利润。

重点在于解题思路,算出每天的差价,正数相加为最大利润。
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 2:return 0
        p_dlist = []
        for i in range(1,len(prices)):
            p_dlist.append(prices[i]-prices[i-1])
        sum = 0
        for i in range(len(p_dlist)):
            if p_dlist[i] > 0:
                sum+=p_dlist[i]
        return sum

还有一种思路,不计算差值,而是在原数组中寻找波峰波谷,波谷买入,波峰卖出,这种方法时间复杂度和空间复杂度应该都是远大于上述方法的,而且判定条件过多,例如数组长度小于3,卖出早于买入,买入晚于卖出,而且会遇到第一天和最后一天无法判断,需要单独用条件语句讨论等问题。我编译没有通过,报错是索引超过列表长度。
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 2:return 0
        if len(prices) == 2:
            if prices[1] > prices[0]:return prices[1]-prices[0]
            else:return 0
        buylist = []
        selllist = []
        for i in range(1,len(prices)-1):
            if prices[i]>prices[i+1]&prices[i-1]<prices[i]:
                selllist.append(i)
            if prices[i]<prices[i+1]&prices[i-1]>pricse[i]:
                buylist.append(i)
        if len(buylist)>0:
            first = buylist[0]
            for j in range(first):
                if prices[j] < prices[buylist[0]]:
                    buylist[0] = j
        else:buylist.append(0)
        if len(selllist)>0:
            last = selllist[-1]
            for k in range(last,len(prices)):
                if prices[k] > prices[selllist[-1]]:
                    selllist[-1] = k
        else:selllist.append(len(prices)-1)
        if selllist[0] > buylist[0]:
            del selllist[0]
        if buylist[-1] > buylist[-1]:
            del buylist[-1]
        sum = 0
        for num in range(len(buylist)):
            sum += prices[selllist[num]] - prices[buylist[num]]
        return sum
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值