Open In App

Longest equal substring with cost less than K

Improve
Improve
Like Article
Like
Save
Share
Report

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








Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given string.

Efficient Approach:

Our Approach is simple and we can reduce the space complexity from O(n) to O(1) that is constant space .

Approach:

  1.  We maintain a sliding window of length len that starts at index 0 and ends at index i.
  2.  We calculate the total cost of changing the characters within this window and compare it with the given cost K.
  3.  If the total cost is less than or equal to K, we update the maximum length seen so far. If the total cost is greater than K, we shrink the window from the left to decrease the cost until it becomes less than or equal to K.
  4. To calculate the cost of changing the characters at each index i, we use the absolute difference between the ASCII value of the characters.
  5. Hence we return the maxlen as our Output.

Implementation:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum length up to which X can be changed to Y within the given cost K.
int max_Length(string X, string Y, int K) {
   int n = X.size();
   int cost = 0, len = 0, maxlen = 0;
   for (int i = 0; i < n; i++) {
       cost += abs(X[i] - Y[i]); // calculate the cost of changing the characters at each index i within the window.
       len++;
       while (cost > K) { // if the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
           cost -= abs(X[i - len + 1] - Y[i - len + 1]);
           len--;
       }
       maxlen = max(maxlen, len); // update the maximum length seen so far.
   }
   return maxlen;
}
 
int main() {
    
   string X="abcd", Y="bcde";
   int K=3;
 
   // call the maxLength function and print the result
   int result = max_Length(X, Y, K);
   cout << result << "\n";
 
   return 0;
}


Java




import java.util.*;
 
public class GFG {
    // Function to find the maximum length up to which X can be changed to Y within the given cost K.
    public static int maxLength(String X, String Y, int K) {
        int n = X.length();
        int cost = 0, len = 0, maxlen = 0;
        for (int i = 0; i < n; i++) {
            cost += Math.abs(X.charAt(i) - Y.charAt(i)); // calculate the cost of changing the characters at each index i within the window.
            len++;
            while (cost > K) { // if the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
                cost -= Math.abs(X.charAt(i - len + 1) - Y.charAt(i - len + 1));
                len--;
            }
            maxlen = Math.max(maxlen, len); // update the maximum length seen so far.
        }
        return maxlen;
    }
 
    public static void main(String[] args) {
        String X = "abcd";
        String Y = "bcde";
        int K = 3;
 
        // Call the maxLength function and print the result
        int result = maxLength(X, Y, K);
        System.out.println(result);
    }
}


Python3




# Function to find the maximum length up to which
# X can be changed to Y within the given cost K.
def max_length(X, Y, K):
    n = len(X)
    cost = 0
    length = 0
    max_length = 0
 
    for i in range(n):
         # calculate the cost of changing the characters at
         # each index i within the window.
        cost += abs(ord(X[i]) - ord(Y[i]))
        length += 1
        # if the total cost of changing the characters within
        # the window is more than K, shrink the window from the left
        # to decrease the cost.
        while cost > K: 
            cost -= abs(ord(X[i - length + 1]) - ord(Y[i - length + 1]))
            length -= 1
 
        max_length = max(max_length, length)  # update the maximum length seen so far.
 
    return max_length
 
def main():
    X = "abcd"
    Y = "bcde"
    K = 3
 
    # call the max_length function and print the result
    result = max_length(X, Y, K)
    print(result)
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program {
    // Function to find the maximum length up to which X can
    // be changed to Y within the given cost K.
    static int MaxLength(string X, string Y, int K)
    {
        int n = X.Length;
        int cost = 0, len = 0, maxlen = 0;
        for (int i = 0; i < n; i++) {
            cost += Math.Abs(
                X[i]
                - Y[i]); // calculate the cost of changing
                         // the characters at each index i
                         // within the window.
            len++;
            while (cost > K) {
                // if the total cost of changing the
                // characters within the window is more than
                // K, shrink the window from the left to
                // decrease the cost.
                cost -= Math.Abs(X[i - len + 1]
                                 - Y[i - len + 1]);
                len--;
            }
            maxlen = Math.Max(maxlen,
                              len); // update the maximum
                                    // length seen so far.
        }
        return maxlen;
    }
 
    static void Main(string[] args)
    {
        string X = "abcd", Y = "bcde";
        int K = 3;
 
        // call the MaxLength function and print the result
        int result = MaxLength(X, Y, K);
        Console.WriteLine(result);
 
        // Keep the console window open until a key is
        // pressed
        Console.ReadKey();
    }
}


Javascript




// Function to find the maximum length up to which X can be changed to
// Y within the given cost K.
function max_Length(X, Y, K) {
  // Calculate the length of the string.
  const n = X.length;
 
  // Initialize the cost, length, and maximum length variables.
  let cost = 0;
  let len = 0;
  let maxlen = 0;
 
  // Iterate over the string.
  for (let i = 0; i < n; i++) {
    // Calculate the cost of changing the characters at each index i within the window.
    cost += Math.abs(X.charCodeAt(i) - Y.charCodeAt(i));
 
    // Increase the length of the window.
    len++;
 
    // While the total cost of changing the characters within the window is more than K, shrink the window from the left to decrease the cost.
    while (cost > K) {
      // Decrease the cost by subtracting the cost of changing the character at the leftmost index of the window.
      cost -= Math.abs(X.charCodeAt(i - len + 1) - Y.charCodeAt(i - len + 1));
 
      // Decrease the length of the window.
      len--;
    }
 
    // Update the maximum length seen so far.
    maxlen = Math.max(maxlen, len);
  }
 
  // Return the maximum length up to which X can be changed to Y within the given cost K.
  return maxlen;
}
 
// Example usage:
const X = "abcd";
const Y = "bcde";
const K = 3;
 
// Call the max_Length function to find the maximum length up to which X can be changed to Y within the given cost K.
const result = max_Length(X, Y, K);
 
// Print the result.
console.log(result);


Output

3









Time Complexity:  O(N), where N is the length of the input strings X and Y. 

Auxiliary Space: O(1), No extra space is being used.



Last Updated : 11 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads