Find the smallest positive integer value that cannot be represented as sum of any subset of a given array in Python


Suppose we have a sorted array of positive numbers, this array is sorted in ascending order, er have to find the smallest positive value that cannot be represented as sum of elements of any subset of given set. We have to solve this problem in O(n) time.

So, if the input is like A = [1, 4, 8, 12, 13, 17], then the output will be 2.

To solve this, we will follow these steps −

  • n := size of A

  • answer := 1

  • for i in range 0 to n, do

    • if A[i] <= answer, then

      • answer := answer + A[i]

    • otherwise,

      • come out from the loop

  • return answer

Example

Let us see the following implementation to get better understanding −

 Live Demo

def get_smallest_element(A):
   n = len(A)
   answer = 1
   for i in range (0, n ):
      if A[i] <= answer:
         answer = answer + A[i]
      else:
         break
   return answer
A = [1, 4, 8, 12, 13, 17]
print(get_smallest_element(A))

Input

[1, 4, 8, 12, 13, 17]

Output

2

Updated on: 27-Aug-2020

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements