![]() |
VOOZH | about |
Given two strings s1 and s2 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 s1 can be changed to s2 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 = |s1[i] - s2[i]|
Examples:
Input: s1 = abcd, s2 = bcde, k = 3
Output: 3
Explanation: The first three characters can be changed with cost = 1 + 1 + 1.Input: s1 = "xyzabcd", s2 = "bcdfxyw", k = 5
Output: 4
Explanation : abcd can be changed to match bcdf because the total cost to change these characters is 1 + 1 + 1 + 2 = 5, which is within k.Input: s1 = "abcd", s2 = "cdef", k = 3
Output: 1
Explanation: A maximum of 1 character can be changed because the cost to change each character is 2, and taking more than one character would exceed the total cost K.
Table of Content
This approach uses a prefix sum array to store the cumulative cost of converting
s1tos2. Then, using a two-pointer technique, we find the longest substring whose cost does not exceedk.
The prefix array helps in calculating the cost of any substring in O(1) time.
Below is the implementation of the above approach:
3
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given string.
This approach uses the sliding window technique to find the maximum length of a substring such that the total cost of converting
s1tos2does not exceedk. We maintain a window with two pointers and keep track of the current cost. If the cost exceeds k, we shrink the window from the left until it becomes valid again
Implementation:
3