Coding Problem: Array GFG ( Leve 1) SubArray with Given Sum
Approach 1 :
Time Complexity : n2
write two loops and then with the subArray calculate sum and compare to s if it is equal to sum then add in the list and return the index.
Approach 2 :
This is pending
Approach 1 : Solution
class Solution
{
//Function to find a continuous sub-array which adds up to a given number.
static ArrayList<Integer> subarraySum(int[] arr, int n, int s)
{
// Your code here
ArrayList<Integer> list=new ArrayList<Integer>();
int sum=0,i=0,j=0;
for(;i<n;i++) {
for(j=i;j<n;j++) {
sum=sum+arr[j];
if(sum>s) {
break;
}
if(sum==s) {
list.add(i+1);
list.add(j+1);
return list;
}
}
sum=0;
}
list.add(-1);
return list;
}
}