-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_common_sum.cpp
More file actions
44 lines (40 loc) · 899 Bytes
/
longest_common_sum.cpp
File metadata and controls
44 lines (40 loc) · 899 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
#include <bits/stdc++.h>
using namespace std;
int longestCommonSum(int arr1[], int arr2[], int n)
{
/*Time complexitiex ===>O(n)
space com ==> O(n)
*/
int temp[n];
for (int i = 0; i < n; i++)
{
temp[i] = (arr1[i] - arr2[i]);
}
int max_len = 0;
int sum = 0;
unordered_map<int, int> m;
for (int i = 0; i < n; i++)
{
sum += temp[i];
if (sum == 0)
{
max_len = i + 1;
}
if (m.find(sum) != m.end())
{
max_len = max(max_len, i - m[sum]);
}
else
{
m.insert({sum, i});
}
}
return max_len;
}
int main()
{
int arr1[] = {0,0,1,0,0,0,0,1,1,1,0,0,0,0,0,1,0,0,1,1};
int arr2[] = {1,1,1,1,1,1,1,0,0,0,1,1,1,0,1,1,0,1,0,0};
cout<<longestCommonSum(arr1 ,arr2,sizeof(arr1) / sizeof(arr1[0]));
return 0;
}