Skip to content
Related Articles

Related Articles

Improve Article

Longest equal substring with cost less than K

  • Last Updated : 10 Jun, 2021

Given two strings X and Y of the same length, which consist of lowercase letters and also an integer K. The task is to find the maximum length up to which X can be changed to Y within the given cost K
The cost of changing a character is given by the absolute difference between the ASCII value of the characters. That is, to change a character at index i, cost = |x[i] – Y[i]|

Examples: 

Input: X = abcd, Y = bcde, K = 3 
Output:
Explanation: A maximum of 3 characters can be changed because the cost to change each article is 1.  

Approach: The idea is to maintain a prefix array of length N to store the absolute sum of the strings. That is, the cost of changing the string X to Y. The following steps can be followed to compute the result: 

  • Maintain two pointers, say i and j.
  • In a while loop, check if the difference between ith index and jth index of prefix array is greater than given cost or not.
  • If the difference is greater than the given cost, then increase the j pointer to compensate for the cost, else increase the i pointer.

Below is the implementation of the above approach:



C++




// C++ program to find the
// maximum length of equal substring
// within a given cost
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum length
int solve(string X, string Y, int N, int K)
{
 
    int count[N + 1] = { 0 };
    int sol = 0;
    count[0] = 0;
 
    // Fill the prefix array with
    // the difference of letters
    for (int i = 1; i <= N; i++) {
 
        count[i] = count[i - 1] + abs(X[i - 1] - Y[i - 1]);
    }
 
    int j = 0;
 
    for (int i = 1; i <= N; i++) {
        while ((count[i] - count[j]) > K) {
 
            j++;
        }
 
        // Update the maximum length
        sol = max(sol, i - j);
    }
 
    return sol;
}
 
// Driver code
int main()
{
 
    int N = 4;
 
    string X = "abcd", Y = "bcde";
 
    int K = 3;
 
    cout << solve(X, Y, N, K) << "\n";
 
    return 0;
}

Java




// Java program to find the
// maximum length of equal subString
// within a given cost
class GFG
{
 
// Function to find the maximum length
static int solve(String X, String Y,
                int N, int K)
{
 
    int []count = new int[N + 1];
    int sol = 0;
    count[0] = 0;
 
    // Fill the prefix array with
    // the difference of letters
    for (int i = 1; i <= N; i++)
    {
 
        count[i] = count[i - 1] +
                Math.abs(X.charAt(i - 1) -
                Y.charAt(i - 1));
    }
 
    int j = 0;
 
    for (int i = 1; i <= N; i++)
    {
        while ((count[i] - count[j]) > K)
        {
            j++;
        }
 
        // Update the maximum length
        sol = Math.max(sol, i - j);
    }
 
    return sol;
}
 
// Driver code
public static void main(String[] args)
{
 
    int N = 4;
    String X = "abcd", Y = "bcde";
    int K = 3;
 
    System.out.print(solve(X, Y, N, K) + "\n");
}
}
 
// This code is contributed by PrinciRaj1992

Python3




# Python3 program to find the
# maximum length of equal subString
# within a given cost
 
# Function to find the maximum length
def solve(X, Y, N, K):
    count = [0] * (N + 1);
    sol = 0;
    count[0] = 0;
 
    # Fill the prefix array with
    # the difference of letters
    for i in range(1, N + 1):
        count[i] = (count[i - 1] +
                    abs(ord(X[i - 1]) -
                    ord(Y[i - 1])));
 
    j = 0;
 
    for i in range(1, N + 1):
        while ((count[i] - count[j]) > K):
            j += 1;
 
        # Update the maximum length
        sol = max(sol, i - j);
 
    return sol;
 
# Driver code
if __name__ == '__main__':
    N = 4;
    X = "abcd";
    Y = "bcde";
    K = 3;
 
    print(solve(X, Y, N, K));
 
# This code is contributed by PrinciRaj1992

C#




// C# program to find the
// maximum length of equal subString
// within a given cost
using System;
 
class GFG
{
     
    // Function to find the maximum length
    static int solve(string X, string Y,
                    int N, int K)
    {
     
        int []count = new int[N + 1];
        int sol = 0;
        count[0] = 0;
     
        // Fill the prefix array with
        // the difference of letters
        for (int i = 1; i <= N; i++)
        {
     
            count[i] = count[i - 1] +
                    Math.Abs(X[i - 1] -
                    Y[i - 1]);
        }
     
        int j = 0;
     
        for (int i = 1; i <= N; i++)
        {
            while ((count[i] - count[j]) > K)
            {
                j++;
            }
     
            // Update the maximum length
            sol = Math.Max(sol, i - j);
        }
     
        return sol;
    }
 
    // Driver code
    public static void Main()
    {
     
        int N = 4;
        string X = "abcd", Y = "bcde";
        int K = 3;
     
        Console.WriteLine(solve(X, Y, N, K) + "\n");
    }
}
 
// This code is contributed by AnkitRai01

Javascript




<script>
    // Javascript program to find the
    // maximum length of equal subString
    // within a given cost
     
    // Function to find the maximum length
    function solve(X, Y, N, K)
    {
       
        let count = new Array(N + 1);
        count.fill(0);
        let sol = 0;
        count[0] = 0;
       
        // Fill the prefix array with
        // the difference of letters
        for (let i = 1; i <= N; i++)
        {
       
            count[i] = count[i - 1] +
                    Math.abs(X[i - 1].charCodeAt() -
                    Y[i - 1].charCodeAt());
        }
       
        let j = 0;
       
        for (let i = 1; i <= N; i++)
        {
            while ((count[i] - count[j]) > K)
            {
                j++;
            }
       
            // Update the maximum length
            sol = Math.max(sol, i - j);
        }
       
        return sol;
    }
     
    let N = 4;
    let X = "abcd", Y = "bcde";
    let K = 3;
 
    document.write(solve(X, Y, N, K));
         
</script>
Output: 
3

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :