Program to find maximum sum of the subsequence, where difference of two values is same as their position difference in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we select a subsequence of strictly increasing values, where the differences of each two numbers is the same as the differences of their two indices. So we have to find the maximum sum of such a subsequence.

So, if the input is like nums = [6, 7, 9, 9, 8, 5], then the output will be 22, as we select the subsequence [6, 7, 9] whose indices are [0, 1, 3]. The differences between each consecutive numbers is [1, 2] which is same as the differences of their indices.

To solve this, we will follow these steps −

  • d := an empty map

  • for each index i and value x in nums, do

    • d[x − i] := d[x − i] + x

  • return maximum of all values in d

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, nums):
      from collections import defaultdict
      d = defaultdict(int)
      for i, x in enumerate(nums):
         d[x − i] += x
      return max(d.values())

ob1 = Solution()
nums = [6, 7, 9, 9, 8, 5]


[6, 7, 9, 9, 8, 5]


Published on 21-Oct-2020 11:18:30