forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest-Sub-Array-With-Sum-K
37 lines (35 loc) · 1.03 KB
/
Longest-Sub-Array-With-Sum-K
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
while(t-- > 0)
{
String s[] = bf.readLine().trim().split(" ");
int n = Integer.parseInt(s[0]);
int k = Integer.parseInt(s[1]);
s = bf.readLine().trim().split(" ");
int arr[] = new int[n];
for(int i=0 ; i<n ; i++)
arr[i] = Integer.parseInt(s[i]);
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
hm.put(0,-1);
int sum = 0, max = 0;
for(int i=0 ; i<n ; i++)
{
sum += arr[i];
if(hm.containsKey(sum - k))
{
max = Math.max(max, i - hm.get(sum - k) );
}
if(!hm.containsKey(sum))
hm.put(sum, i);
}
System.out.println(max);
}
}
}