We want to find the longest substring where the total transformation cost stays within the budget. The transformation cost at each position is the absolute difference between the ASCII values of the corresponding characters. By checking every possible substring and tracking its cost, we can find the maximum valid length.
i, try extending the substring to the right.|s[j] - t[j]| for each new character.maxCost, stop extending from this start.Since we want the longest contiguous substring within a cost budget, a sliding window is ideal. We expand the window by moving the right pointer and shrink it from the left when the cost exceeds the budget. This efficiently explores all valid windows in linear time.
l and r at the start, and a running curCost of 0.r and adding |s[r] - t[r]| to curCost.curCost exceeds maxCost, shrink the window by subtracting |s[l] - t[l]| and incrementing l.r - l + 1.class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
curCost = 0
l = 0
res = 0
for r in range(len(s)):
curCost += abs(ord(s[r]) - ord(t[r]))
while curCost > maxCost:
curCost -= abs(ord(s[l]) - ord(t[l]))
l += 1
res = max(res, r - l + 1)
return resWe can simplify the sliding window by never shrinking it more than one position at a time. Once we find a valid window of size k, we only care about finding windows of size k+1 or larger. If the current window is invalid, we slide both pointers together, maintaining the window size. The final answer is derived from the position of the left pointer l.
l = 0 and iterate r from 0 to n-1.|s[r] - t[r]| from maxCost.maxCost goes negative, add back |s[l] - t[l]| and increment l by one.n - l as the result.When computing the transformation cost between characters, you must use the absolute difference |s[i] - t[i]|. Forgetting to take the absolute value will produce negative costs when t[i] < s[i], leading to incorrect results. Always wrap the difference in abs() or Math.abs().
In the standard sliding window approach, when the cost exceeds the budget, you should shrink the window from the left one step at a time while updating the running cost. A common mistake is resetting the left pointer to right + 1 or incorrectly jumping the left pointer, which skips valid substrings and produces suboptimal answers.
The problem asks for the maximum length found across all valid windows, not the final window size. Make sure to track and update a separate result variable with max(result, r - l + 1) after each expansion, rather than just returning r - l + 1 at the end of the loop.