In this HackerEarth Largest Substring problem solution, You are given a string S of length N. Each character of the string is either 0 or 1. Now, you need to select the largest substring in which the count of 0 in the string is more than the count of 1. Print the maximum possible length of the subarray in the output.


HackerEarth Largest Substring problem solution


HackerEarth Largest Substring problem solution.

#include<bits/stdc++.h>
#define LL long long int
#define M 1000000007
#define endl "\n"
#define eps 0.00000001
LL pow(LL a,LL b,LL m){ a%=m;LL x=1,y=a;while(b > 0){if(b%2 == 1){x=(x*y);if(x>m) x%=m;}y = (y*y);if(y>m) y%=m;b /= 2;}return x%m;}
LL gcd(LL a,LL b){if(b==0) return a; else return gcd(b,a%b);}
LL gen(LL start,LL end){LL diff = end-start;LL temp = rand()%start;return temp+diff;}
using namespace std;
int zero[100001];
int one[100001];
int temp[100001];
int mini[100001];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
string s;
cin >> s;
s = " " + s;
for(int i = 1; i <= n; i++) {
zero[i] = zero[i - 1];
one[i] = one[i - 1];
if(s[i] == '0')
++zero[i];
if(s[i] == '1')
++one[i];
temp[i] = zero[i] - one[i];
mini[i] = min(mini[i - 1] , temp[i]);
}
int ans = 0;
for(int i = 1; i <= n; i++) {
int l = 0, r = i;
while(l <= r) {
int mid = (l + r) / 2;
if(mini[mid] < temp[i]) {
ans = max(ans , i - mid);
r = mid - 1;
}
else{
l = mid + 1;
}
}
}
cout << ans;
}

Second solution

#include <bits/stdc++.h>

using namespace std;

const int N = 1E5 + 5;
int f1[N];
int f2[N];
int dx[N];
vector<int> a;
vector<int> b;

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
string s;
cin >> n >> s;
int ones = 0;
int zeroes = 0;
for(int i = 0; i < n; i ++) {
s[i] == '1' ? ones ++ : zeroes ++;
f1[i] = ones;
f2[i] = zeroes;
}
for(int i = 0; i < n; i ++) {
a.push_back(f2[i - 1] - f1[i - 1]);
b.push_back(f2[i] - f1[i]);
}
int ans = 0;
int max_val = INT_MIN;
for(int i = n - 1; i >= 0; i --) {
max_val = max(max_val, b[i]);
dx[i] = max_val;
int idx = -1;
int L = i, R = n - 1;
while(L <= R) {
int mid = (L + R) >> 1;
if(dx[mid] > a[i]) {
L = mid + 1;
idx = max(idx, mid);
}
else
R = mid - 1;
}
ans = max(ans, idx - i + 1);
}
cout << ans;
return 0;
}