-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLongest_Sub-Array_with_Sum_K.java
62 lines (47 loc) · 1.08 KB
/
Longest_Sub-Array_with_Sum_K.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Longest Sub-Array with Sum K
Input : arr[] = { 10, 5, 2, 7, 1, 9 },
K = 15
Output : 4
The sub-array is {5, 2, 7, 1}.
*/
/*package whatever //do not write package name here */
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
//code
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t-->0) {
int n=s.nextInt();
int k=s.nextInt();
int arr[] = new int[n];
for(int i=0;i<arr.length;i++) {
arr[i] = s.nextInt();
}
HashMap<Integer , Integer> map = new HashMap<>();
int sum=0,ml=0;
for(int i=0;i<arr.length;i++) {
sum+=arr[i];
if(sum == k) {
ml=i+1;
}
if(!map.containsKey(sum)){
map.put(sum,i);
// System.out.println("i::"+i);
}
if(map.containsKey(sum-k))
{
int x=map.get(sum-k);
//System.out.println(x);
if(ml<i-x){
ml=i-x;
}
}
}
System.out.println(ml);
}
}
}