Python 中买卖股票的最佳时机 II
pythonserver side programmingprogramming更新于 2025/10/26 23:40:17
假设我们有一个数组 A,这里 A[i] 表示第 i 天某只股票的价格。我们必须找到最大的利润。我们可以完成任意数量的交易。(交易意味着买卖股票)。但我们必须记住,我们可能不能同时进行多笔交易。所以我们必须先卖掉股票,然后再买入新股票。
假设数组是这样的 A = [7, 1, 5, 3, 6, 4],那么结果将是 7。我们可以看到,如果我们在第 2 天(索引 1)买入,那么它将以 1 作为买入价格。那么如果我们在第 3 天卖出,利润将是 5 – 1 = 4。然后在第 4 天买入,在第 5 天卖出,所以利润将是 6 – 3 = 3
要解决这个问题,请按照以下步骤 −
- 让 answer = 0
- 对于 i 在 0 到 n – 1 范围内(n 是 A 中的元素数)−
- 如果 A[i] – A[i – 1] > 0,则
- answer := answer + A[i] – A[i – 1]
- 如果 A[i] – A[i – 1] > 0,则
- 返回 answer
示例
让我们看看实现以获得更好的理解
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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

