Skip to content

Instantly share code, notes, and snippets.

@vinodjayachandran
Created August 14, 2020 18:12
Show Gist options
  • Save vinodjayachandran/b86419e5f3d4e11106ff2f85850e2bcf to your computer and use it in GitHub Desktop.
Save vinodjayachandran/b86419e5f3d4e11106ff2f85850e2bcf to your computer and use it in GitHub Desktop.
Subarray with given sum - Given an unsorted array A of size N of non-negative integers, find the first occurrence of continuous sub-array which adds to a given number S. Print the start and end index (0 based) as output
import java.util.Scanner;
public class SubArrayWithGivenSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Array as space separated String");
String [] inputStrArray = input.nextLine().split(" ");
// Convert String array to int array
int [] inputIntArray = new int[inputStrArray.length];
for(int i=0;i<inputStrArray.length;i++) {
inputIntArray[i] = Integer.parseInt(inputStrArray[i]);
}
System.out.println("Enter the desired sum");
int sum = input.nextInt();
for(int start = 0; start<inputIntArray.length;start++) {
int currentSum = inputIntArray[start];
for(int end = start+1; end<inputIntArray.length;end++) {
currentSum = currentSum + inputIntArray[end];
if(currentSum<sum)
continue;
else if (currentSum>sum)
break;
else {
System.out.printf("Array Index Range %s from %s ", start,end);
System.exit(0);
}
}
}
input.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment