forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_subarray_with_sum_k.cpp
More file actions
65 lines (43 loc) · 882 Bytes
/
longest_subarray_with_sum_k.cpp
File metadata and controls
65 lines (43 loc) · 882 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include<iostream>
#include<unordered_map>
using namespace std;
int longestsubarry(int arr[],int n,int k){
// csum, index
unordered_map<int, int> m;
int pre = 0;
int len = 0;
for(int i=0;i<n;i++){
pre += arr[i];
if(pre==k){
//i+1 because 0 based indexing
len = max(len, i+1);
}
//repeating number
if(m.find(pre-k)!=m.end()){
//i - first occurence of csum
len = max(len, i - m[pre-k]); }
else{
//store the first occ
m[pre] = i;
}
}
return len;
}
int main(){
int n,k;
cin >> n>>k;
int arr[n];
for(int i=0;i<n;i++){
cin >> arr[i];
}
cout<<longestsubarry(arr,n,k);
return 0;
}
/*
Test case :
Input :
6 15
10 5 2 7 1 9
Output :
4
*/