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]
come out from the loop
Let us see the following implementation to get better understanding −
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))
[1, 4, 8, 12, 13, 17]