Problem 305
Smallest Sum That Cannot Be Formed
Medium · 20 pts · Array, Greedy, Sorting
Problem
You have N coins with positive values. Using each coin at most once, you can pay any amount that equals the sum of some subset of the coins. Find the smallest positive amount that you cannot pay exactly. For example, with coins 1 and 3 you can pay 1, 3 and 4, but not 2, so the answer is 2. The empty subset does not count, so the smallest amount you could hope to pay is 1.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. All values are positive.
Output
Print the smallest positive integer that is not the sum of any subset.
Constraints
1 <= N <= 100000; 1 <= A[i] <= 1000000000 (the answer fits in a 64-bit integer)
Example input
4 1 2 5 10
Example output
4
Explanation
With coins 1 2 5 10 you can pay 1, 2 and 3 (1 + 2), but nothing adds up to 4: the only coins smaller than 4 are 1 and 2. So 4 is the smallest amount you cannot pay.