https://leetcode.com/problems/get-equal-substrings-within-budget/
- Sliding Window
Sliding window tracking cost to convert substring; expand right and shrink left if cost exceeds budget.
O(n)
O(1)
class Solution {
public int equalSubstring(String s, String t, int maxCost) {
int left = 0, cost = 0, ans = 0;
for (int right = 0; right < s.length(); right++) {
cost += Math.abs(s.charAt(right) - t.charAt(right));
while (cost > maxCost) {
cost -= Math.abs(s.charAt(left) - t.charAt(left));
left++;
}
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}