Find the Contiguous Subarray with Sum to a Given Value in an array in Java

Given an array of positive integer and given value X, find Contiguous sub array whose sum is equal to X.
For example :

arr[]={14, 12, 70, 15, 99, 65, 21, 90}; 
X =97.
Sum found between index 1 to 3
Elements are 12, 17 and 15
static void findSubArraySumEqualToX(int arr[], int X) {
 int currentSum;
 for (int i = 0; i < arr.length; i++) {
 currentSum = arr[i];
 // try all subarrays starting with 'i'
 for (int j = i + 1; j <= arr.length; j++) {
 if (currentSum == X) {
 int endIndexForContArray = j - 1;
 System.out.println("Sum found between indexes " + i + " and " + endIndexForContArray);
 for (int k = i; k <= endIndexForContArray; k++) {
 System.out.print(arr[k]+" ");
 }
 return;
 }
 if (currentSum > X || j == arr.length)
 break;
 currentSum = currentSum + arr[j];
 }
 }
 
 System.out.println("No subarray found");
 return;
 }
 

Leave a Comment