-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest sub-array with sum K
57 lines (45 loc) · 1.5 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//Longest sub-array with sum K
import java.io.*;
import java.util.*;
class Array {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(br.readLine());
while(testcases-- > 0) {
String line = br.readLine();
String[] element = line.trim().split("\\s+");
int sizeOfArray = Integer.parseInt(element[0]);
int K = Integer.parseInt(element[1]);
int arr [] = new int[sizeOfArray];
line = br.readLine();
String[] elements = line.trim().split("\\s+");
for(int i = 0;i<sizeOfArray;i++) {
arr[i] = Integer.parseInt(elements[i]);
}
Solution obj = new Solution();
int res = obj.lenOfLongSubarr(arr, sizeOfArray, K);
System.out.println(res);
}
}
}
class Solution{
public static int lenOfLongSubarr (int A[], int N, int K) {
Map<Integer, Integer> map = new HashMap<>();
int sum = 0;
int maxLen = 0;
for(int i = 0; i < A.length; i++) {
sum += A[i];
if(sum == K) {
maxLen = Math.max(maxLen, i + 1);
}
int rem = sum - K;
if(map.containsKey(rem)) {
maxLen = Math.max(maxLen, i - map.get(rem));
}
if(!map.containsKey(sum)) {
map.put(sum, i);
}
}
return maxLen;
}
}