Skip to content

Instantly share code, notes, and snippets.

@anil477
Created October 5, 2019 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/3abcc4767c93c602213f64fd35fb0e08 to your computer and use it in GitHub Desktop.
Save anil477/3abcc4767c93c602213f64fd35fb0e08 to your computer and use it in GitHub Desktop.
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
class FindSmallestInteger {
public static void main(String[] args) {
int arr3[] = {1, 1, 1, 3};
System.out.println(findMinImpossible(arr3));
}
public static int findMinImpossible(int[] a) {
int maxPossible = 0;
if (a.length == 0 || a[0] != 1) {
return maxPossible + 1;
}
// we have verified that 1 exists in the array.
maxPossible = 1;
for (int i = 1; i < a.length; i++) {
// if the current element is greater than (maxPossible + 1)
// that leaves a gap at: maxPossible + 1
if (a[i] > maxPossible + 1) {
break;
}
maxPossible += a[i];
}
return maxPossible + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment