用 Python 编写程序,通过持有和出售获利来找出最大利润
pythonserver side programmingprogramming更新于 2026/1/5 15:40:17
假设我们有一个名为 nums 的数字列表,它按时间顺序表示一家公司的股票价格。我们每天最多可以买入一股股票,但你可以持有多只股票,并且可以在任意天数出售股票。返回您可以获得的最大利润。
因此,如果输入为 nums = [3, 4, 7, 3, 5],则输出将为 9,因为我们可以在 3 和 4 时买入股票,然后在 7 时卖出。然后再次以 3 买入,以 5 卖出。总利润 (7 - 3) + (7 - 4) + (5 - 3) = 9。
为了解决这个问题,我们将遵循以下步骤 −
- ans := 0
- 当 nums 不为空时,执行
- top := 从 nums 中删除最后一个元素
- 当 nums 不为空且 top > nums 的最后一个元素,执行
- ans := ans + (top - nums 中的最后一个元素)
- 从 nums 中删除最后一个元素
- 返回 ans
示例
让我们看看下面的实现以便更好地理解 −
def solve(nums): ans = 0 while nums: top = nums.pop() while nums and top > nums[-1]: ans += top - nums.pop() return ans nums = [3, 4, 7, 3, 5] print(solve(nums))
输入
[3, 4, 7, 3, 5]
输出
9
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

