Input: [1,2,3,10]Output: 7Explanation: All numbers from 1 to 6 can be represented using subsets of the array. For example:1=[1],2=[2],3=[3],4=[1,3],5=[2,3],6=[1,2,3].7 cannot be formed using subsets of the array.
Input: [1,3,6,10,11,15]Output: 2Explanation: The smallest positive integer that cannot be represented is2 since 1 can be made using [1], but no subset adds up to 2.
The problem can be approached iteratively by considering the cumulative sum constructively:
Start with the assumption that 1 is the smallest positive integer not representable using subsets of the array.
Traverse the array and see if the current number in the array extends the range of representable sums. If it does, update the range.
If a gap is found between the current smallest non-representable integer and the next number in the array, that gap is the answer.
For example:
If the smallest positive integer not representable is x and the current array element is y, check if y ≤ x. If true, update x to x + y since subsets including y can also represent more integers.
If y > x, x remains the answer as y cannot build up the smallest integer x.
Initialising a variable smallestMissing to 1 (to represent the smallest positive integer not yet representable).
Iterating through the array and updating smallestMissing:
If the current array element is less than or equal to smallestMissing, then update smallestMissing to include all possible sums with the current element.
If the current element is greater than smallestMissing, then break out of the loop as smallestMissing cannot be reached by any subset.
classSolution:
deffindSmallestMissingInteger(self, arr):
smallestMissing =1# Initialise smallest positive integer not representablefor num in arr:
if num <= smallestMissing:
smallestMissing += num # Extend the range of representable sumselse:
break# 'num' creates a gap at smallestMissingreturn smallestMissing
# Example Usage:solution = Solution()
print(solution.findSmallestMissingInteger([1, 2, 3, 10])) # Output: 7print(solution.findSmallestMissingInteger([1, 3, 6, 10, 11, 15])) # Output: 2print(solution.findSmallestMissingInteger([1, 1, 1, 4])) # Output: 8