-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestSubarray.java
More file actions
52 lines (48 loc) · 1.18 KB
/
longestSubarray.java
File metadata and controls
52 lines (48 loc) · 1.18 KB
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
public class longestSubarray{
public static void main(String[] args)
{
int[] arr={2,3,5,1,9};
int n=arr.length;
int k=9;
Approach obj=new Approach();
// Approach 1
// Find the length of the longest subarray with sum k
int result=obj.approach1(arr, n, k);
System.out.println("The length of the longest subarray with sum " + k + " is: " + result);
}
}
class Approach{
int approach1(int[] arr, int n, int k)
{
int maxLength=0;
int sum=0;
int start=0;
for(int i=0; i<n; i++)
{
sum=0;
start=1;
sum+=arr[i];
try{
int j=i+1;
while(sum< k)
{
sum+=arr[j];
start++;
j++;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
break;
}
finally
{
if(sum==k)
{
maxLength= Math.max(start, maxLength);
}
}
}
return maxLength;
}
}