[InterviewBit] Longest Subarray Length

Longest Subarray Length

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
int Solution::solve(vector<int> &A) {
int res = 0, now = 0;
unordered_map<int, int> freq{{0,-1}};
for(int i = 0; i < A.size(); i++) {
now += A[i] ? 1 : -1;
if(!freq.count(now)) freq[now] = i;
if(freq.count(now - 1)) res = max(res, i - freq[now-1]);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/08/PS/Codeforces/longest-subarray-length/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.