fork(2) download
  1. //My program assumes 0 based indexing
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5. {
  6. int T;
  7. cin>>T;
  8. while(T--)
  9. {
  10. int N; //Length of String str
  11. cin>>N;
  12. string str;
  13. cin>>str; //String of length N and contains lowerCase Alphabets only
  14. int maxlength = 0; //Initially assume 0 length if no subsequnece cant be selected
  15. int freq[26]; //Frequency Array storing last visited position of lowercase alphabets
  16. for(int i = 0;i<26;i++)
  17. {
  18. freq[i] = -1; //Initialisation of frequency array to -1 to indicate no character has previously occured .0 is not used because 0 is used in indexing the string .
  19. }
  20. for(int i = 0;i<N;i++){
  21. int code = str[i]-'a'; //mapped to 0,1..26 to indicate a,b...z
  22. if(freq[code]!=-1) //if already this character is present before
  23. {
  24. maxlength = max(N-(i-freq[code]-1)-1,maxlength); //Considering N-(j-i) for all possible i,j where str[i]==str[j] and i!=j
  25. }
  26. freq[code] = i; //Updating last visited position of the lowercase alphabet
  27. }
  28. cout<<maxlength<<"\n"; //Outputting the maximum length possible of the sub-sub-sequences as answer
  29. }
  30. }
Runtime error #stdin #stdout 0s 4460KB
stdin
Standard input is empty
stdout
Standard output is empty