Easy to Understand || Sliding Window & 2 Pointers || C++ || Java || Python || Javascript
Complexity

Time complexity:
O(n)


Space complexity:
O(1)

Code
# Complexity

- Time complexity:
$$O(n)$$

- Space complexity:
$$O(1)$$

# Code
```cpp []
class Solution {
public:
    int equalSubstring(string s, string t, int maxCost) {

        int n = s.length();
        int l = 0;
        int r = 0;

        int cost = 0;
        int maxLen = 0;

        while(r < n) {

            cost += abs(int(s[r]) - int(t[r]));

            while(cost > maxCost) {
                cost -= abs(int(s[l]) - int(t[l]));
                l++;
            } 

            maxLen = max(maxLen, r-l+1);
            r++;
        }

        return maxLen;
    }
};
```
```Java []
class Solution {
    public int equalSubstring(String s, String t, int maxCost) {
        int n = s.length();
        int l = 0, r = 0, cost = 0, maxLen = 0;

        while (r < n) {
            cost += Math.abs(s.charAt(r) - t.charAt(r));
            
            while (cost > maxCost) {
                cost -= Math.abs(s.charAt(l) - t.charAt(l));
                l++;
            }
            
            maxLen = Math.max(maxLen, r - l + 1);
            r++;
        }
        
        return maxLen;
    }
}

```
```python []
class Solution(object):
    def equalSubstring(self, s, t, maxCost):
        """
        :type s: str
        :type t: str
        :type maxCost: int
        :rtype: int
        """

        n = len(s)
        l = r = cost = maxLen = 0

        while r < n:
            cost += abs(ord(s[r]) - ord(t[r]))

            while cost > maxCost:
                cost -= abs(ord(s[l]) - ord(t[l]))
                l += 1

            maxLen = max(maxLen, r - l + 1)
            r += 1

        return maxLen
        
```
```javascript []
/**
 * @param {string} s
 * @param {string} t
 * @param {number} maxCost
 * @return {number}
 */
var equalSubstring = function(s, t, maxCost) {
    let n = s.length;
    let l = 0, r = 0, cost = 0, maxLen = 0;

    while (r < n) {
        cost += Math.abs(s.charCodeAt(r) - t.charCodeAt(r));

        while (cost > maxCost) {
            cost -= Math.abs(s.charCodeAt(l) - t.charCodeAt(l));
            l++;
        }

        maxLen = Math.max(maxLen, r - l + 1);
        r++;
    }

    return maxLen;
};

```
['Two Pointers', 'Sliding Window', 'Python', 'C++', 'Java', 'JavaScript']