Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Find Maximum Sum of Subsequence in Python



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 −

Example

 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]
print(ob1.solve(nums))

Input

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

Output

22
Updated on: 2020-10-21T11:19:19+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements