![]() |
VOOZH | about |
Given an array of positive numbers, the task is to find the smallest positive integer value that cannot be represented as the sum of elements of any subset of a given set.
Examples:
Input: arr[] = {1, 10, 3, 11, 6, 15};
Output: 2
Explanation: 2 is the smallest positive number for which no subset is there with sum 2.Input: arr[] = {1, 1, 1, 1};
Output: 5
Explanation: 5 is the smallest positive number for which no subset is there with sum 5.Input: arr[] = {1, 1, 3, 4};
Output: 10
Explanation: 10 is the smallest positive number for which no subset is there with sum 10.
Table of Content
The solution uses dynamic programming similar to the Subset Sum problem. First, compute the total sum of the array and create a boolean DP array where dp[s] indicates whether sum s can be formed. Initialize dp[0] = true (empty subset). For each element, update the DP array to mark new reachable sums. Finally, scan the DP array to find the smallest index with false, which is the smallest sum that cannot be formed.
consider the following dry run: arr = {1, 2, 3}
Now we can form: {0,1,2,3,4,5,6} so final answer : 7
2
The idea is to sort the array and maintain the smallest sum res that cannot be formed so far. Initialize res = 1, meaning we cannot form 1 initially. Traverse the sorted array: if the current element arr[i] is greater than res, then res is the smallest missing sum. Otherwise, include arr[i] and extend the reachable range by updating res += arr[i]. This works because if we can form all sums from 1 to resβ1, adding arr[i] lets us form sums up to res + arr[i] β 1.
Consider the following dry run: arr = {1, 3, 2}
Final answer : 7
2