Skip to content

Commit b79b6c6

Browse files
maximum length of sub-array
1 parent 4d34882 commit b79b6c6

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
import java.util.*;
3+
4+
public class maxLength_Of_Subarray {
5+
6+
public static void main(String[] args) {
7+
Scanner sc = new Scanner(System.in);
8+
int n = sc.nextInt();
9+
int k = sc.nextInt();
10+
int[] arr = new int[n];
11+
for(int i = 0; i < n; i++){
12+
arr[i] = sc.nextInt();
13+
}
14+
System.out.println(countSubarrays(arr,n,k));
15+
sc.close();
16+
}
17+
18+
public static int countSubarrays(int[] arr, int n, int k) {
19+
20+
HashMap<Integer, Integer> map = new HashMap<>();
21+
int sum = 0, maxLen = 0; // sum = prefix sum which stores sum of every element, maxlen = maximum length of sub array
22+
for(int i = 0; i < n; i++){
23+
sum += arr[i];
24+
if(sum==k){
25+
maxLen = i + 1; // if k itself is present in the array then length will start from 0 to index of k
26+
}
27+
if(!map.containsKey(sum)){ // putting frequencies of every sum
28+
map.put(sum, i);
29+
}
30+
if(map.containsKey(sum-k)){
31+
if(maxLen < (i-map.get(sum-k))){ // updating the maxlen variable from starting point of sub array to end point
32+
maxLen = i - map.get(sum-k);
33+
}
34+
}
35+
}
36+
37+
return maxLen;
38+
39+
}
40+
41+
}

0 commit comments

Comments
 (0)