July 2021

D - Hawkeye's Conundrum

Solution

\[\]

Implementation

#include<bits/stdc++.h>
#define ll long long
using namespace std;

int main()
    {
      int t;
      cin>>t;
      
      while(t--)
      {
         ll n;
         cin>>n;
         
         string s;
         cin>>s;
         
         vector<ll> A(26);
         for(ll &i:A)
            cin>>i;
            
         vector<ll> b(26,0);
         // An array to count the no.of occurences of each lowercase letters in the string
         
         ll i=0,j=0,pos,maxm=-1;

         while(j<n) {
         // the loop continues until j reaches end of the string
         
            if(b[s[j]-'a']<A[s[j]-'a']) {
                // checks if no. of occurence of letters at position j doesn't exceed A[s[j]-'a']
        
                b[s[j]-'a']++; 
                
                if((j-i+1)>maxm) {
                    maxm=j-i+1;
                    pos=i;
                }
                
                /*      
                checks whether the formed substring is the maximum 
                possible among all checked substrings until now and
                updates the maximum length and the substring
                */

                j++;
            }
            
            else {
                b[s[i]-'a']--;
                i++;
            }
            
            /*
            as the substring length is decresed as we increased i so we
            decrement the occurence by one as it is later not appeared in any
            next iterations
            */
         }

         cout<<maxm<<endl;
         cout<<s.substr(pos,maxm)<<endl;
      }
}
\[\]

Contest Material