Check if is possible to get given sum from a given set of elements in Python


Suppose we have an array called nums and another value sum. We have to check whether it is possible to get sum by adding elements present in nums, we may pick a single element multiple times.

So, if the input is like nums = [2, 3, 5] sum = 28, then the output will be True as we can get 26 by using 5 + 5 + 5 + 5 + 3 + 3 + 2

To solve this, we will follow these steps −

  • MAX := 1000
  • table := an array of size MAX ad fill with 0
  • Define a function util() . This will take nums
  • table[0] := 1
  • sort the list nums
  • for i in range 0 to size of nums - 1, do
    • val := nums[i]
    • if table[val] is non-zero, then
      • go for next iteration
    • for j in range 0 to MAX - val - 1, do
      • if table[j] is non-zero, then
        • table[j + val] := 1
  • From the main method do the following −
  • util(nums)
  • if table[sum] is non-zero, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

MAX = 1000
table = [0] * MAX
def util(nums):
   table[0] = 1
   nums.sort()
   for i in range(len(nums)):
      val = nums[i]
      if table[val]:
         continue
      for j in range(MAX - val):
         if table[j]:
            table[j + val] = 1
def solve(nums, sum):
   util(nums)
   if table[sum]:
      return True
   return False
nums = [2, 3, 5]
sum = 28
print (solve(nums, sum))

Input

[2, 3, 5], 28

Output

True

Updated on: 18-Jan-2021

393 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements