forked from SR-Sunny-Raj/Hacktoberfest2021-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Largest_Subarray_Of_K_sum.java
53 lines (39 loc) · 1005 Bytes
/
Largest_Subarray_Of_K_sum.java
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
/*
Given an array containing N integers and an integer K., Your task is to find the length of the longest Sub-Array
with the sum of the elements equal to the given value K.
Input :
A[] = {10, 5, 2, 7, 1, 9}
K = 15
Output : 4
Explanation:
The sub-array is {5, 2, 7, 1}.
*/
import java.io.*;
import java.util.*;
class LongSubarray{
static int lenOfLongSubarray(int[] arr, int n, int k)
{
HashMap<Integer, Integer> mp = new HashMap<>();
int sum = 0, maxLen = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
if (sum == k)
maxLen = i + 1;
if (!mp.containsKey(sum)) {
mp.put(sum, i);
}
if (mp.containsKey(sum - k)) {
if (maxLen < (i - mp.get(sum - k)))
maxLen = i - mp.get(sum - k);
}
}
return maxLen;
}
public static void main(String args[])
{
int[] arr = {10, 5, 2, 7, 1, 9};
int n = arr.length;
int k = 15;
System.out.println(lenOfLongSubarray(arr, n, k));
}
}