- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestsubarray.java
More file actions
Latest commit
29 lines (24 loc) · 585 Bytes
/
Copy pathlongestsubarray.java
File metadata and controls
29 lines (24 loc) · 585 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
publicclasslongestsubarray {
publicstaticintsubarray(int[] nums, intk) {
intlength=0;
intn=nums.length;
for(inti=0;i<n;i++){
//i=0to4 1,2,1=3
//i=1to4 2,1,0,1=4
intsum=0;
for(intj=i;j<n;j++){
sum+=nums[j];
if(sum==k){
length=Math.max(length,j-i+1);//3,4
}
}
}
returnlength;
}
publicstaticvoidmain(String[] args) {
int[] nums = {1,2,1,0,1};
intk = 4;
intmaxlength = subarray(nums, k);
System.out.println("Longest subarray length is "+maxlength);
}
}