Get Equal Substrings Within Budget
Difficulty: Medium · Pattern: Sliding Window · LeetCode #1208
s and t have equal length. Changing s[i] to t[i] costs |ord(s[i]) − ord(t[i])|. Return the maximum length of a substring of s that can be changed into the corresponding substring of t with total cost ≤ maxCost.
Examples
text
s = "abcd", t = "bcdf", maxCost = 3 → 3
s = "abcd", t = "cdef", maxCost = 3 → 1
s = "abcd", t = "acde", maxCost = 0 → 1Hints
- Convert to an array of non-negative costs; find the longest subarray with sum ≤ maxCost.
Approach
Costs are non-negative, so the sliding window works: add cost[r]; while the total exceeds maxCost, subtract cost[l] and advance l; track the maximum length. O(n).
Complexity
Time: O(n). Space: O(1).
Python solution
def equalSubstring(s, t, maxCost):
l = total = best = 0
for r in range(len(s)):
total += abs(ord(s[r]) - ord(t[r]))
while total > maxCost:
total -= abs(ord(s[l]) - ord(t[l])); l += 1
best = max(best, r - l + 1)
return bestJavaScript solution
function equalSubstring(s, t, maxCost) {
let l = 0, total = 0, best = 0;
const c = (i) => Math.abs(s.charCodeAt(i) - t.charCodeAt(i));
for (let r = 0; r < s.length; r++) {
total += c(r);
while (total > maxCost) total -= c(l++);
best = Math.max(best, r - l + 1);
}
return best;
}