在 Python 中,最多更新元素三次后,找出最大值和最小值的最小差值程序
pythonserver side programmingprogramming更新于 2026/2/1 19:56:17
假设我们有一个名为 nums 的数字列表,现在考虑一个可以将元素更新为任意值的操作。我们最多可以执行 3 次这样的操作,我们必须找到 nums 中最大值和最小值之间的最小差异。
因此,如果输入为 nums = [2, 3, 4, 5, 6, 7],则输出将为 2,因为我们可以将列表更改为 [4, 3, 4, 5, 4, 4],然后 5 - 3 = 2。
为了解决这个问题,我们将遵循以下步骤 −
- 如果 nums 的大小 <= 4,则
- 返回 0
- n := nums 的大小
- 对列表 nums 进行排序
- 返回 nums[n-4 + i] - nums[i] 之间差异的最小值,其中 i 为范围 0 至 3
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): if len(nums) <= 4: return 0 nums.sort() return min(nums[-4 + i] - nums[i] for i in range(4)) ob = Solution() nums = [2, 3, 4, 5, 6, 7] print(ob.solve(nums))
输入
[2, 3, 4, 5, 6, 7]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

