fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <set>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int longestValidSubstring(const string& s, int k) {
  9. int n = s.length();
  10. multiset<char> st;
  11. int i = 0;
  12. int j = 0;
  13. int maxLength = 0;
  14.  
  15. while (j < n) {
  16. // Expand the window by adding the current character
  17. st.insert(s[j]);
  18.  
  19. // Shrink the window from the left if the max difference exceeds k
  20. while (*st.rbegin() - *st.begin() > k) {
  21. st.erase(st.find(s[i]));
  22. ++i;
  23. }
  24.  
  25. // Update the maximum length found so far
  26. maxLength = max(maxLength, j - i + 1);
  27. j++;
  28. }
  29.  
  30. return maxLength;
  31. }
  32.  
  33. int main() {
  34. // Example 1
  35. string s1 = "abdfa";
  36. int k1 = 2;
  37. cout << "String: " << s1 << ", k = " << k1 << "\n";
  38. cout << "Longest Valid Substring Length: " << longestValidSubstring(s1, k1) << "\n\n";
  39. // Explanation: "ab" (diff 1), "bd" (diff 2), "df" (diff 2) are valid. Max length is 2.
  40.  
  41. // Example 2
  42. string s2 = "edcba";
  43. int k2 = 2;
  44. cout << "String: " << s2 << ", k = " << k2 << "\n";
  45. cout << "Longest Valid Substring Length: " << longestValidSubstring(s2, k2) << "\n";
  46. // Explanation: "edc" (diff 'e'-'c' = 2), "dcb" (diff 2), "cba" (diff 2). Max length is 3.
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
String: abdfa, k = 2
Longest Valid Substring Length: 2

String: edcba, k = 2
Longest Valid Substring Length: 3