-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestCommonSumInTwoBinaryArray.cpp
More file actions
49 lines (44 loc) · 1.06 KB
/
longestCommonSumInTwoBinaryArray.cpp
File metadata and controls
49 lines (44 loc) · 1.06 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
#include<bits/stdc++.h>
using namespace std;
// longest common span with same sum in two binary array
void naive(vector<int> a, vector<int> b){
int ans = 0;
for(int i = 0; i < a.size(); i++){
int s1 = 0, s2 = 0;
for(int j = i; j < b.size(); j++){
s1 += a[j];
s2 += b[j];
if(s1 == s2){
ans = max(ans, j-i+1);
}
}
}
cout << ans << endl;
}
void optimal(vector<int> a, vector<int> b){
vector<int> temp;
for(int i = 0; i < a.size(); i++){
temp.push_back(a[i]-b[i]);
}
int psum = 0;
int ans = 0;
unordered_map<int, int> m;
for(int i = 0; i < temp.size(); i++){
psum += temp[i];
if(psum == 0){
ans = max(ans, i+1);
}
if(m.find(psum) != m.end()){
ans = max(ans, i-m[psum]);
}
m.insert(make_pair(psum, i));
}
cout << ans << endl;
}
int main(){
vector<int> a = {0, 1, 0, 0, 0, 0};
vector<int> b = {1, 0, 1, 0, 0, 1};
// ans = 4;
optimal(a, b);
return 0;
}