import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class FindSubArr {
public static void main(String[] args) {
int [] arr = {0,1,2,3,4,5,6,9,2,1,1,1,10,2,2,2};
int s = 6 ;
int [] sub = findLongestSubArray( arr,s);
System.out.println("longest SubArray Range ==> "+Arrays.toString(sub));
}
public static int[] findLongestSubArray(int [] arr, int s){
int[] result = new int[]{-1};
int sum=0,left=0,right=0;
while(right < arr.length){
sum += arr[right];
while(left < right && sum > s){
sum -= arr[left++];
}
if(sum == s && (result.length == 1 || result[1] - result[0] < right - left)){
result = new int[]{left + 1, right +1};
}
right++;
}
return result;
}
}
class SubarraySum {
/* Returns true if the there is
a subarray of arr[] with sum equal to
'sum' otherwise returns false.
Also, prints the result */
int subArraySum(int arr[], int n, int sum)
{
int currentSum = arr[0], start = 0, i;
// Pick a starting point
for (i = 1; i <= n; i++) {
// If currentSum exceeds the sum,
// then remove the starting elements
while (currentSum > sum && start < i - 1) {
currentSum = currentSum - arr[start];
start++;
}
// If currentSum becomes equal to sum,
// then return true
if (currentSum == sum) {
int p = i - 1;
System.out.println(
"Sum found between indexes " + start
+ " and " + p);
return 1;
}
// Add this element to curr_sum
if (i < n)
currentSum = currentSum + arr[i];
}
System.out.println("No subarray found");
return 0;
}
public static void main(String[] args)
{
SubarraySum arraysum = new SubarraySum();
int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
int n = arr.length;
int sum = 23;
arraysum.subArraySum(arr, n, sum);
}
}
// This code has been contributed by Mayank
// Jaiswal(mayank_24)