fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to find the maximum length
  5. // continuous segment of character c after
  6. // flipping at most K characters
  7. int maxLength(string str, int n,
  8. char c, int k)
  9. {
  10. // Stores the maximum length
  11. int ans = -1;
  12.  
  13. // Stores the count of char 'c'
  14. int cnt = 0;
  15.  
  16. // Start of window
  17. int left = 0;
  18.  
  19. for (int right = 0; right < n; right++) {
  20.  
  21. if (str[right] == c) {
  22. cnt++;
  23. }
  24.  
  25. // Remove the extra 'c' from left
  26. while (cnt > k) {
  27. if (str[left] == c) {
  28. cnt--;
  29. }
  30.  
  31. // Increment the value of
  32. // the left
  33. left++;
  34. }
  35.  
  36. // Update the resultant maximum
  37. // length of character ch
  38. ans = max(ans, right - left + 1);
  39. }
  40.  
  41. return ans;
  42. }
  43.  
  44. // Function to find the maximum length
  45. // of consecutive 0s or 1s by flipping
  46. // at most K characters of the string
  47. int maxConsecutiveSegment(string S, int K)
  48. {
  49. int N = S.length();
  50.  
  51. // Print the maximum of the maximum
  52. // length of 0s or 1s
  53. return max(maxLength(S, N, '0', K),
  54. maxLength(S, N, '1', K));
  55. }
  56.  
  57. // Driver Code
  58. int main()
  59. {
  60. string S = "1001";
  61. int K = 1;
  62. cout << maxConsecutiveSegment(S, K);
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
3