GFG question, Need help

https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0
this is the question,

/*
Example:
Input:
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output:
2 4
1 5
*/

import java.util.*;
import java.lang.*;
import java.io.*;

class Main{
public static void main (String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
    int size=sc.nextInt();
    int sum=sc.nextInt();
    int[] arr=new int[size];
    for(int i=0;i<size;i++) arr[i]=sc.nextInt();

    int i=0;int j=0;
    boolean flag=false;
    int amt=arr[i];;
    while(i<=j&&j<=size-1){
             if(sum==amt){
              
               flag=true;break;}

             else if(sum<amt){
                amt=amt-arr[i++];
            }
            else if(sum>amt&&j!=size-1){amt=amt+arr[++j];}
            else if(j==size-1){
                amt=amt+arr[j];
                if(amt<sum) break;
                else amt=amt-arr[j];
            }

        }
        j++;
        if(flag){System.out.println(i+1+" "+j);}
        else System.out.println(-1);

     }
  }
}

i am applying the same logic which the GFG mentioned in their tutorials, still TLE showing, can anyone help me, where i am getting wrong.

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	long long t, n, s;
	cin >>t;
	while(t--){
		cin >>n >>s;
		vector<long long> arr(n);
		for(long long i = 0; i < n; i++)
			cin >>arr[i];
		long long curr = arr[0], start = 0;
		bool flag = true;
		for(long long i = 1; i <= n; i++){
			// if current sum exceeds the required sum, 
			// remove the starting elements
			while(curr > s && start < i - 1){
				curr -= arr[start];
				start++;
			}
			if(curr == s){
				// sum found
				cout <<start + 1 <<" " <<i <<"\n";
				flag = false;
				break;
			}
			// add current element to current sum
			if(i < n)
			    curr += arr[i];
		}
		// required sum was not found
		if(flag)
		    cout <<-1 <<"\n";
	}
	return 0;
}

can be easily solved using the sliding window technique.

1 Like