- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements