DEV Community

Cover image for ๐—ฆ๐˜๐—ฟ๐—ฒ๐—ฎ๐—ธ- ๐Ÿฎ ๐—Ÿ๐—ฒ๐—ฒ๐˜๐—–๐—ผ๐—ฑ๐—ฒ- ๐—š๐—ฒ๐˜ ๐—˜๐—พ๐˜‚๐—ฎ๐—น ๐—ฆ๐˜‚๐—ฏ๐˜€๐˜๐—ฟ๐—ถ๐—ป๐—ด๐˜€ ๐—ช๐—ถ๐˜๐—ต๐—ถ๐—ป ๐—•๐˜‚๐—ฑ๐—ด๐—ฒ๐˜
Pranjal Sailwal
Pranjal Sailwal

Posted on

๐—ฆ๐˜๐—ฟ๐—ฒ๐—ฎ๐—ธ- ๐Ÿฎ ๐—Ÿ๐—ฒ๐—ฒ๐˜๐—–๐—ผ๐—ฑ๐—ฒ- ๐—š๐—ฒ๐˜ ๐—˜๐—พ๐˜‚๐—ฎ๐—น ๐—ฆ๐˜‚๐—ฏ๐˜€๐˜๐—ฟ๐—ถ๐—ป๐—ด๐˜€ ๐—ช๐—ถ๐˜๐—ต๐—ถ๐—ป ๐—•๐˜‚๐—ฑ๐—ด๐—ฒ๐˜

class Solution {
    public int equalSubstring(String s, String t, int maxCost) {
        int n = s.length();
        int[] cost = new int[n];
        for (int i = 0; i < n; i++) {
            cost[i] = Math.abs(s.charAt(i) - t.charAt(i));
        }
        int maxLength = 0;
        int currentCost = 0;
        int windowStart = 0;
        for (int windowEnd = 0; windowEnd < n; windowEnd++) {
            currentCost += cost[windowEnd];
            while (currentCost > maxCost) {
                currentCost -= cost[windowStart];
                windowStart++;
            }
            maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
        }
        return maxLength;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐—ข๐—ฝ๐—ฒ๐—ป ๐˜๐—ผ ๐—จ๐—ฝ๐—ฑ๐—ฎ๐˜๐—ฒ๐˜€ ๐—ฎ๐—ป๐—ฑ ๐—ฆ๐˜‚๐—ด๐—ด๐—ฒ๐˜€๐˜๐—ถ๐—ผ๐—ป๐˜€

Top comments (0)