-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlenOfsubArray.cpp
54 lines (43 loc) · 881 Bytes
/
lenOfsubArray.cpp
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
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int lenOfSubArray(vector<int> &, int);
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int len = lenOfSubArray(arr, 15);
cout << len;
return 0;
}
int lenOfSubArray(vector<int> &nums, int k)
{
unordered_map<int, int> mpp;
int sum = 0;
int maxSum = 0;
for (int i = 0; i < nums.size(); i++)
{
sum += nums[i];
if (sum == k)
{
maxSum = max(i + 1, maxSum);
}
int val = sum - k;
if (mpp.find(val) != mpp.end())
{
int temp = i - mpp[val];
maxSum = max(maxSum, temp);
}
if (mpp.find(sum) == mpp.end())
{
mpp[sum] = i;
}
}
return maxSum;
}