I can search for subarrays with sum eqaul to k for positive numbers but the below code fails for negative numbers in arrays. Is there an algorithm for finding subarrays with a given sum for negative and positive numbers in an array ?
public static void subarraySum(int[] arr, int sum) {
int start=0;
int currSum=arr[0];
for(int i = 1;i<=arr.length;i++) {
while(currSum>sum ) {
currSum-=arr[start];
start++;
}
if(currSum==sum) {
System.out.println(start + " " + (i-1) + " index");
start=i;
currSum=0;
}
if(i<arr.length) {
currSum +=arr[i];
}
}
}
For example, {10, 2, -2, -20, 10}, find subarray with sum -10 in this array. Subarray in this case would be {-20, 10}.