fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. inline int power(int a, int b) {
  6. int x = 1;
  7. while (b) {
  8. if (b & 1) x *= a;
  9. a *= a;
  10. b >>= 1;
  11. }
  12. return x;
  13. }
  14.  
  15.  
  16. const int M = 1000000007;
  17. const int N = 3e5+9;
  18. const int INF = 2e9+1;
  19. const int LINF = 2000000000000000001;
  20.  
  21. //_ ***************************** START Below *******************************
  22.  
  23. // In Good Subarrays problem, draw array && subarray and apply Maths and find condition
  24.  
  25. // L R
  26. // [ _ _ _ _ _ (_ _ _ _ _ _) _ _ ]
  27.  
  28.  
  29. // Given : Px[R] - Px[L-1] == Py[R] - Py[L-1]
  30. // cnt of x == cnt of y in subarray [L,R]
  31. // Px[R]-Py[R] == Px[L-1] - Py[L-1]
  32. // Hence find for Px[R] - Py[R] in past
  33.  
  34.  
  35. vector<int> a;
  36. void consistency(int n) {
  37.  
  38. int ones = 0;
  39. int zeroes = 0;
  40.  
  41. unordered_map<int, int> mp = {{0, -1}};
  42. int ans = 0;
  43. for(int i=0; i<n; i++){
  44. if(a[i] == 0) zeroes++;
  45. else ones++;
  46.  
  47. if(mp.count(zeroes-ones)){
  48. int l = mp[zeroes-ones];
  49. int len = i-l;
  50. ans = max(ans, len);
  51. }
  52. if(!mp.count(zeroes-ones)) mp[zeroes-ones] = i;
  53.  
  54. }
  55.  
  56. cout << ans << endl;
  57. }
  58.  
  59. void solve() {
  60.  
  61. int n;
  62. cin >> n;
  63. a.resize(n);
  64. for(int i=0; i<n; i++) cin >> a[i];
  65. consistency(n) ;
  66.  
  67. }
  68.  
  69.  
  70.  
  71.  
  72.  
  73. int32_t main() {
  74. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  75.  
  76. int t = 1;
  77. cin >> t;
  78. while (t--) {
  79. solve();
  80. }
  81.  
  82. return 0;
  83. }
Success #stdin #stdout 0.01s 5320KB
stdin
4
2
0 1
3
0 1 0
9
0 1 1 1 1 1 0 0 0
8
0 0 1 0 0 0 1 1
stdout
2
2
6
6