用 Python 编写程序来查找一对 (i, j),其中 nums[i] + nums[j] + (i -j) 最大化?
pythonserver side programmingprogramming更新于 2026/2/16 15:08:17
假设我们有一个名为 nums 的数字列表,我们必须找到一对 (i, j),其中 i < j,并且 nums[i] + nums[j] + (i - j) 最大化。
因此,如果输入为 nums = [6, 6, 2, 2, 2, 8],则输出将为 11,因为如果我们选择两个 6,则其分数为 6 + 6 + 0 - 1 = 11。
要解决这个问题,我们将遵循以下步骤:
large := nums[0]
maxi := 0
对于范围从 1 到 nums 大小的 i,执行
large := large - 1
maxi := large + nums[i] 的最大值和maxi
large := large 和 nums[i] 的最大值
返回 maxi
让我们看看下面的实现以便更好地理解
示例
class Solution: def solve(self, nums): large = nums[0] maxi = 0 for i in range(1, len(nums)): large -= 1 maxi = max(large + nums[i], maxi) large = max(large, nums[i]) return maxi ob = Solution() nums = [6, 6, 2, 2, 2, 8] print(ob.solve(nums))
输入
[6, 6, 2, 2, 2, 8]
输出
11
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

