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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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
• if n is same as 2, then
• return minimum of nums and nums
• table := a list of size n and fill with 0
• table := nums
• table := nums
• table := nums
• 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
if n == 2:
return min(nums, nums)
table =  * n

table = nums
table = nums
table = nums

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