Program to find a pair (i, j) where nums[i] + nums[j] + (i -j) is maximized in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to find a pair (i, j) where i < j, and nums[i] + nums[j] + (i - j) is maximized.

So, if the input is like nums = [6, 6, 2, 2, 2, 8], then the output will be 11, as if we pick the two 6 then its score is 6 + 6 + 0 - 1 = 11.

To solve this, we will follow these steps:

  • large := nums[0]

  • maxi := 0

  • for i in range 1 to size of nums, do

    • large := large - 1

    • maxi := maximum of large + nums[i] and maxi

    • large := maximum of large and nums[i]

  • return maxi

Let us see the following implementation to get better understanding

Example

 Live Demo

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))

Input

[6, 6, 2, 2, 2, 8]

Output

11
raja
Published on 10-Nov-2020 09:10:15
Advertisements