💯Beats 97%💯 Faster✅ Sliding Window 🔥🎯Java☕
Intuition\nTo find the maximum length of a substring that can be transformed within a given cost, we can utilize a sliding window approach. By maintaining a win
# Intuition\nTo find the maximum length of a substring that can be transformed within a given cost, we can utilize a sliding window approach. By maintaining a window with two pointers, we can efficiently calculate the cost of transforming the substring and adjust the window size to maximize the length without exceeding the given cost.\n\n# Approach\n1. Calculate Differences:\n\nFirst, compute the absolute differences between corresponding characters of the strings s and t. Store these differences in an array arr.\n\n2. Sliding Window:\n\n- Initialize two pointers, l and r, both starting at the beginning of the array.\n- Use a variable sum to keep track of the current transformation cost of the substring within the window [l, r].\n- Expand the window by moving r to the right and adding the difference to sum as long as the sum does not exceed maxCost.\n- If the sum exceeds maxCost, shrink the window by moving l to the right and subtracting the corresponding difference from sum.\nKeep track of the maximum length of the window that satisfies the condition.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n\n# Code\n```\nclass Solution {\n    public int equalSubstring(String s, String t, int maxCost) {\n        int n=s.length();\n        int arr[]=new int[n];\n        for(int i=0;i<n;i++)\n        {\n            arr[i]=Math.abs(s.charAt(i)-t.charAt(i));\n\n        }\n        int count=-1;\n        int sum=0;\n        int l=0;\n        int r=0;\n      \n        while(l<=n-1)\n        { \n             \n         if(r<n&&sum+arr[r]<=maxCost)\n         {\n             sum=sum+arr[r];\n              int c=r-l+1;\n             count = (c > count) ? c : count;\n               r++;\n         }\n         else\n         {\n            sum=sum-arr[l];\n            l++;\n         }\n\n        }\n        return count;\n    }\n}\n```\n![upvote.jpeg](https://assets.leetcode.com/users/images/98b3f377-9d8e-49bf-b830-7374b0abf29d_1717239542.4382093.jpeg)
['Java']