Created
October 5, 2019 14:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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