首页 文章资讯内容详情

用Python买卖股票II的最佳时间

2026-06-04 1 花语

假设我们有一个数组A,这里A[i]表示第i天给定股票的价格。我们必须找到最大的利润。我们可以根据需要完成尽可能多的交易。(交易是指买卖股票)。但是我们必须记住,我们可能不会同时进行多项交易。因此,在购买新股票之前,我们必须出售股票。

假设数组像A=[7、1、5、3、6、4],那么结果将是7。如我们所见,如果我们在第2天(索引1)购买,那么它将取1作为购买价格。然后,如果我们在第3天卖出,则利润将为5–1=4。然后在第4天买入,然后在第5天卖出,因此利润将为6–3=3

为了解决这个问题,请遵循以下步骤-

letanswer=0

foriinrange0ton–1(nisthenumberofelementsinA)−

ifA[i]–A[i–1]>0,then

answer:=answer+A[i]–A[i–1]

returnanswer

示例

让我们看一下实现以获得更好的理解

class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ ans = 0 for i in range(1,len(prices)): if prices[i] - prices[i-1] >0: ans+=(prices[i] - prices[i-1]) return ans ob1 = Solution() print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))

输入值

print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))

输出结果

13