Longest equal substring with cost less than K
Last Updated :
11 Oct, 2023
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: 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 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++
#include <bits/stdc++.h>
using namespace std;
int solve(string X, string Y, int N, int K)
{
int count[N + 1] = { 0 };
int sol = 0;
count[0] = 0;
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++;
}
sol = max(sol, i - j);
}
return sol;
}
int main()
{
int N = 4;
string X = "abcd" , Y = "bcde" ;
int K = 3;
cout << solve(X, Y, N, K) << "\n" ;
return 0;
}
|
Java
class GFG
{
static int solve(String X, String Y,
int N, int K)
{
int []count = new int [N + 1 ];
int sol = 0 ;
count[ 0 ] = 0 ;
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++;
}
sol = Math.max(sol, i - j);
}
return sol;
}
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" );
}
}
|
Python3
def solve(X, Y, N, K):
count = [ 0 ] * (N + 1 );
sol = 0 ;
count[ 0 ] = 0 ;
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 ;
sol = max (sol, i - j);
return sol;
if __name__ = = '__main__' :
N = 4 ;
X = "abcd" ;
Y = "bcde" ;
K = 3 ;
print (solve(X, Y, N, K));
|
C#
using System;
class GFG
{
static int solve( string X, string Y,
int N, int K)
{
int []count = new int [N + 1];
int sol = 0;
count[0] = 0;
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++;
}
sol = Math.Max(sol, i - j);
}
return sol;
}
public static void Main()
{
int N = 4;
string X = "abcd" , Y = "bcde" ;
int K = 3;
Console.WriteLine(solve(X, Y, N, K) + "\n" );
}
}
|
Javascript
<script>
function solve(X, Y, N, K)
{
let count = new Array(N + 1);
count.fill(0);
let sol = 0;
count[0] = 0;
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++;
}
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>
|
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:
- We maintain a sliding window of length len that starts at index 0 and ends at index i.
- We calculate the total cost of changing the characters within this window and compare it with the given cost K.
- 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.
- To calculate the cost of changing the characters at each index i, we use the absolute difference between the ASCII value of the characters.
- Hence we return the maxlen as our Output.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
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]);
len++;
while (cost > K) {
cost -= abs (X[i - len + 1] - Y[i - len + 1]);
len--;
}
maxlen = max(maxlen, len);
}
return maxlen;
}
int main() {
string X= "abcd" , Y= "bcde" ;
int K=3;
int result = max_Length(X, Y, K);
cout << result << "\n" ;
return 0;
}
|
Java
import java.util.*;
public class GFG {
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));
len++;
while (cost > K) {
cost -= Math.abs(X.charAt(i - len + 1 ) - Y.charAt(i - len + 1 ));
len--;
}
maxlen = Math.max(maxlen, len);
}
return maxlen;
}
public static void main(String[] args) {
String X = "abcd" ;
String Y = "bcde" ;
int K = 3 ;
int result = maxLength(X, Y, K);
System.out.println(result);
}
}
|
Python3
def max_length(X, Y, K):
n = len (X)
cost = 0
length = 0
max_length = 0
for i in range (n):
cost + = abs ( ord (X[i]) - ord (Y[i]))
length + = 1
while cost > K:
cost - = abs ( ord (X[i - length + 1 ]) - ord (Y[i - length + 1 ]))
length - = 1
max_length = max (max_length, length)
return max_length
def main():
X = "abcd"
Y = "bcde"
K = 3
result = max_length(X, Y, K)
print (result)
if __name__ = = "__main__" :
main()
|
C#
using System;
class Program {
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]);
len++;
while (cost > K) {
cost -= Math.Abs(X[i - len + 1]
- Y[i - len + 1]);
len--;
}
maxlen = Math.Max(maxlen,
len);
}
return maxlen;
}
static void Main( string [] args)
{
string X = "abcd" , Y = "bcde" ;
int K = 3;
int result = MaxLength(X, Y, K);
Console.WriteLine(result);
Console.ReadKey();
}
}
|
Javascript
function max_Length(X, Y, K) {
const n = X.length;
let cost = 0;
let len = 0;
let maxlen = 0;
for (let i = 0; i < n; i++) {
cost += Math.abs(X.charCodeAt(i) - Y.charCodeAt(i));
len++;
while (cost > K) {
cost -= Math.abs(X.charCodeAt(i - len + 1) - Y.charCodeAt(i - len + 1));
len--;
}
maxlen = Math.max(maxlen, len);
}
return maxlen;
}
const X = "abcd" ;
const Y = "bcde" ;
const K = 3;
const result = max_Length(X, Y, K);
console.log(result);
|
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.
Share your thoughts in the comments
Please Login to comment...