Get Equal Substrings Within Budget Problem
Description
LeetCode Problem 1208.
You are given two strings s and t of the same length and an integer maxCost.
You want to change s to t. Changing the i^th character of s to i^th character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).
Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.
Example 1:
Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
Explanation: "abc" of s can change to "bcd".
That costs 3, so the maximum length is 3.
Example 2:
Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.
Example 3:
Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
Explanation: You cannot make any change, so the maximum length is 1.
Constraints:
1 <= s.length <= 10^5t.length == s.length0 <= maxCost <= 10^6sandtconsist of only lowercase English letters.
Solution
Approach: Sliding Window
Changing position i costs |s[i] - t[i]| on its own, no matter what happens elsewhere. So the question is: what is the longest stretch of positions whose costs add up to at most maxCost?
Every cost is non-negative, so a sliding window works. Making the window longer never makes its cost smaller, and making it shorter never makes its cost larger. Move right over the string one position at a time:
- Add
cost(right)to the window's total. - While the total is over
maxCost, removecost(left)and moveleftforward. - Now the window
left..rightfits the budget; record its lengthright - left + 1.
The window can become empty: when a single position costs more than maxCost, left moves past right and the length is 0. That is how the answer 0 arises (e.g. s = "a", t = "z", maxCost = 0).
Each index enters and leaves the window at most once.
Complexity: O(n) time and O(1) extra space.
class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
best = cost = left = 0
for right in range(len(s)):
cost += abs(ord(s[right]) - ord(t[right]))
# Shrink the window from the left until it fits the budget again.
while cost > maxCost:
cost -= abs(ord(s[left]) - ord(t[left]))
left += 1
best = max(best, right - left + 1) # the window may be empty (left = right + 1)
return best