Promi_38

Is it binary search

Jan 9th, 2021
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. /*You are given a string S of length n. You can change atmost k characters from the string into any other character. You target is to find a largest substring which contains all same character.
  2.  
  3. Input Format
  4.  
  5. First line will contain two number n which indicate the length of the string and k.
  6.  
  7. Second line will contain the string S.
  8.  
  9. All characters Si will be lowercase English alphabet.
  10.  
  11. Output Format
  12.  
  13. In a single line print the answer of the question.
  14.  
  15. Sample Input 0
  16.  
  17. 4 1
  18. abac
  19. Sample Output 0
  20.  
  21. 3
  22. Explanation 0
  23.  
  24. S="abac" and k=1.
  25.  
  26. You can change the string into "aaac" or "abaa" or "bbac" or many other ways.
  27.  
  28. If you convert the string into "aaac" it will have a substring "aaa" of length  which is maximum that contain all same characters. So our answer will be */
  29.  
  30. #include <iostream>
  31. using namespace std;
  32.  
  33. int len(char A[], int n, int k, char ch)
  34. {
  35.     int mx_l = 1, c = 0, l = 0, r = 0;
  36.  
  37.     while (r < n)
  38.     {
  39.         if (A[r] != ch) c++;
  40.         while (c > k)
  41.         {
  42.             if (A[l] != ch) c--;
  43.             l++;
  44.         }
  45.         mx_l = max(mx_l, r - l + 1);
  46.         r++;
  47.     }
  48.     return mx_l;
  49. }
  50.  
  51.  
  52. int lrg_substr(char A[], int n, int k)
  53. {
  54.     int mx_l = 1;
  55.     for (int i = 0; i < 26; ++i) {
  56.         mx_l = max(mx_l, len(A, n, k, i + 'A'));
  57.         mx_l = max(mx_l, len(A, n, k, i + 'a'));
  58.     }
  59.     return mx_l;
  60. }
  61.  
  62. int main()
  63. {
  64.  
  65.     int n, k;
  66.     scanf("%d %d", &n, &k);
  67.     char A[n];
  68.     scanf("%s", A);
  69.     printf("%d\n", lrg_substr(A, n, k));
  70. }
Advertisement
Add Comment
Please, Sign In to add comment