Longest equal substring with cost less than K

Given two string X and Y of the same length which consists 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: 3
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 to change 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 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:

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output:

3

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princiraj1992, AnkitRai01

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.