Python程式:尋找一對(i, j),使得nums[i] + nums[j] + (i - j) 最大化?


假設我們有一個名為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

  • 對於 i 從 1 到 nums 的大小,執行:

    • 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

更新於:2020年11月10日

247 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.