Program to find minimum sum subsequence by taking at least one element from consecutive 3 elements in python


Suppose we have a a list of numbers called nums, we have to find a minimum sum subsequence from the given list such that at least one number for all groups of three consecutive numbers is selected. If the length of given list is less than 3, a number should still be selected.

So, if the input is like nums = [2, 3, 4, 5, 6, 7], then the output will be 7, as we can select 2 and 5.

To solve this, we will follow these steps:

  • n := size of nums
  • if n is same as 0, then
    • return 0
  • if n is same as 1, then
    • return nums[0]
  • if n is same as 2, then
    • return minimum of nums[0] and nums[1]
  • table := a list of size n and fill with 0
  • table[0] := nums[0]
  • table[1] := nums[1]
  • table[2] := nums[2]
  • for i in range 3 to n, do
    • table[i] := nums[i] + minimum of table[i - 3], table[i - 2] and table[i - 1]
  • res := minimum of table[n - 1], table[n - 2] and table[n - 3]
  • return res

Let us see the following implementation to get better understanding:

Example Code

Live Demo

class Solution:
   def solve(self, nums):
      n = len(nums)
      if n == 0:
         return 0
      if n == 1:
         return nums[0]
      if n == 2:
         return min(nums[0], nums[1])
      table = [0] * n

      table[0] = nums[0]
      table[1] = nums[1]
      table[2] = nums[2]

      for i in range(3, n):
         table[i] = nums[i] + min(table[i - 3], table[i - 2], table[i - 1])

         res = min(table[n - 1], table[n - 2], table[n - 3])
      return res

ob = Solution()
nums = [2, 3, 4, 5, 6, 7]
print(ob.solve(nums))

Input

[2, 3, 4, 5, 6, 7]

Output

7

Updated on: 25-Nov-2020

694 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements