forked from BasanthreddyA/100DaysOfCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimum length of sub array.java
More file actions
40 lines (32 loc) · 924 Bytes
/
minimum length of sub array.java
File metadata and controls
40 lines (32 loc) · 924 Bytes
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
import java.util.*;
public class Main
{
public static void main(String[] args) {
int[] a={-8, -8, -3, 8};
int target=5;
System.out.println(minimumLength(a,target));
}
static int minimumLength(int a[],int k){
HashMap<Integer,Integer> map=new HashMap<>();
int mini=2147483647;
int sum=0;
for(int i=0;i<a.length;i++){
sum+=a[i];
if(sum==k){
int curr=i+1;
mini=Math.min(mini,curr);
}
int requiredsum=sum-k;
if(map.containsKey(requiredsum)){
int foundid=map.get(requiredsum);
int currentloc=i;
mini=Math.min(mini,currentloc-foundid);
}
map.put(sum,i);
// int key=map.getKey(a[i],i);
//mini=Math.min(mini,key);
}
if(mini>=Integer.MAX_VALUE) return -1;
return mini;
}
}