[LeetCode] Get Equal Substrings Within Budget

1208. Get Equal Substrings Within Budget

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 ith character of s to ith 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int equalSubstring(string s, string t, int maxCost) {
int res = 0, l = 0, r = 0, n = s.length(), sum = 0;

while(r < n) {
while(r < n and sum <= maxCost) {
res = max(res, r - l);
sum += abs(t[r] - s[r]);
r++;
}
if(sum <= maxCost) res = max(res, r - l);

while(sum > maxCost and l < r) {
sum -= abs(t[l] - s[l]);
l++;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/get-equal-substrings-within-budget/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.