Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
public class SubArrayExist {
public static void main(String[] args) {
if(args == null || args.length < 2) {
System.out.println("You must enter the search int n, followed by a space delimited list of numbers that comprises the array");
}
int needle = Integer.valueOf(args[0]); // sum to seek
int[] haystack = new int[args.length - 1];
for(int i = 1; i < args.length; i++) {
haystack[i - 1] = Integer.valueOf(args[i]);
}
System.out.println("Seeking sum: " + needle);
System.out.println(" In array: " + Arrays.toString(haystack));
int currSum = 0;
List<Integer> currValues = new LinkedList<>();
int i = 0;
while(i < haystack.length && currSum != needle) {
if(haystack[i] + currSum <= needle) {
currValues.add(haystack[i]);
currSum += haystack[i];
} else {
if(currValues.size() > 0) {
int removeValue = currValues.get(0);
currSum -= removeValue;
currValues.remove(0);
continue;
}
}
i++;
}
System.out.println("Subarray exists: " + (currSum == needle));
if(currSum == needle) {
System.out.println(Arrays.toString(currValues.toArray()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment