Get Equal Substrings Within Budget - Problem
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 the 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.
Input & Output
Example 1 — Basic Transformation
$
Input:
s = "abcd", t = "bcdf", maxCost = 3
›
Output:
3
💡 Note:
We can change "abc" to "bcd" with cost |a-b| + |b-c| + |c-d| = 1 + 1 + 1 = 3, giving us a substring of length 3.
Example 2 — Single Character
$
Input:
s = "abcd", t = "cdef", maxCost = 3
›
Output:
1
💡 Note:
Each character transformation costs 2, so with maxCost = 3, we can only transform 1 character at a time.
Example 3 — No Budget
$
Input:
s = "abcd", t = "acde", maxCost = 0
›
Output:
1
💡 Note:
Characters 'a' at position 0 match (cost 0), so we can have a substring of length 1 with no cost.
Constraints
- 1 ≤ s.length, t.length ≤ 105
- 0 ≤ maxCost ≤ 106
- s and t contain only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Strings
Two strings s and t of same length, with maxCost budget
2
Calculate Costs
Cost to change s[i] to t[i] is |s[i] - t[i]|
3
Find Maximum Length
Longest substring transformable within budget
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find the longest substring transformable within the given cost budget
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code