➤ Problem Link : 676C. Vasya and String
✅ C++ Solution :
#include<bits/stdc++.h> using namespace std; int main() { int n,k; cin>>n>>k; string s; cin>>s; pair<int,int> cum[n+1]; memset(cum,0,sizeof(cum)); cum[0]=make_pair(0,0); int ac=0,bc=0; for(int i=1;i<=n;i++) { if(s[i-1]=='a') ac++; else bc++; cum[i]=make_pair(ac,bc); } int ans=0; for(int i=0;i<n;i++) { int low=i; int high=n-1; int mid; while(low<high) { mid=low+(high-low+1)/2; int val=min(cum[mid+1].first-cum[i].first,cum[mid+1].second-cum[i].second); if(val<=k) low=mid; else high=mid-1; } ans=max(ans,high-i+1); } cout<<ans; }
Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
😇Happy Learning!!