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)

Sentry image

See why 4M developers consider Sentry, โ€œnot bad.โ€

Fixing code doesnโ€™t have to be the worst part of your day. Learn how Sentry can help.

Learn more

๐Ÿ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay