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]|
Input: X = abcd, Y = bcde, K = 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:
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.
- Length of the longest substring with equal 1s and 0s
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Longest Common Substring | DP-29
- Longest substring with count of 1s more than 0s
- Longest substring of vowels
- Longest Palindromic Substring | Set 1
- Longest Non-palindromic substring
- Longest Palindromic Substring | Set 2
- Longest Even Length Substring such that Sum of First and Second Half is same
- Longest repeating and non-overlapping substring
- Length of the longest valid substring
- Longest substring such that no three consecutive characters are same
- Longest substring having K distinct vowels
- Print the longest common substring
- Length of the longest substring that do not contain any palindrome
- Longest Common Substring in an Array of Strings
- Longest substring of only 4's from the first N characters of the infinite string
- Longest palindromic string possible after removal of a substring
- Longest substring of 0s in a string formed by k concatenations
- SequenceMatcher in Python for Longest Common Substring
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.