Easy C++ Sliding Window Solution⭐💯
Longest Substring with a Maximum Cost\n\n## Intuition\nTo find the longest substring where the sum of absolute differences between corresponding characters of t
# Longest Substring with a Maximum Cost\n\n## Intuition\nTo find the longest substring where the sum of absolute differences between corresponding characters of two strings `s` and `t` does not exceed a given `maxCost`, we can use a sliding window approach. This technique allows us to efficiently manage the range of characters we are considering by expanding and contracting the window based on the cost constraints.\n\n## Approach\n1. Initialize two pointers `start` and `end` to mark the bounds of the sliding window. Also, initialize a variable `sum` to keep track of the current cost.\n2. Expand the window by moving the `end` pointer from left to right.\n3. For each character, calculate the absolute difference between the characters in `s` and `t` at the `end` pointer and add it to `sum`.\n4. If `sum` exceeds `maxCost`, contract the window from the left by moving the `start` pointer to the right and subtracting the corresponding difference from `sum`.\n5. The length of the current valid window is `end - start`. Keep track of the maximum length encountered.\n6. Continue this process until the `end` pointer reaches the end of the string `s`.\n\n## Complexity\n- **Time Complexity:** \\(O(n)\\) where \\(n\\) is the length of the string `s`. This is because each character is processed at most twice (once when expanding the window and once when contracting it).\n- **Space Complexity:** \\(O(1)\\) because we only use a fixed amount of extra space.\n\n## Code\n```cpp\nclass Solution {\npublic:\n    int equalSubstring(string s, string t, int maxCost) {\n        int start = 0, end = 0, sum = 0;\n\n        while (end < s.length()) {\n            sum += abs(s[end] - t[end]);\n            end++;\n\n            if (sum > maxCost) {\n                sum -= abs(s[start] - t[start]);\n                start++;\n            }\n        }\n\n        return end - start;\n    }\n};\n
['String', 'Sliding Window', 'C++']