Java
public class SmallestPositiveInteger {
public static int findSmallestPositiveInteger(int[] nums) {
int smallest = 1;
for (int num : nums) {
if (num <= smallest) {
smallest += num;
} else {
break;
}
}
return smallest;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 10};
int result = findSmallestPositiveInteger(nums);
System.out.println(result); // Output: 7
}
}
Javascript
function findSmallestPositiveInteger(nums) {
let smallest = 1;
for (let num of nums) {
if (num <= smallest) {
smallest += num;
} else {
break;
}
}
return smallest;
}
const nums = [1, 2, 3, 10];
const result = findSmallestPositiveInteger(nums);
console.log(result); // Output: 7
Python:
def find_smallest_positive_integer(nums):
smallest = 1
for num in nums:
if num <= smallest:
smallest += num
else:
break
return smallest
nums = [1, 2, 3, 10]
result = find_smallest_positive_integer(nums)
print(result) # Output: 7
The solution iterates through the sorted array and updates the value of the smallest
variable. It adds each number from the array to smallest
if the number is less than or equal to smallest
. If the number is greater than smallest
, it breaks out of the loop. Finally, it returns the value of smallest
, which represents the smallest positive integer that cannot be formed by a subset of the given sorted array.
Asked by: Amazon