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 ofsthat can be changed to be the same as the corresponding substring oftwith a cost less than or equal tomaxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.
Assume we have a window bound by left and right. We will track currCost to see if are using the maxCost optimally. We will extend the right boundary, and update the current cost, and keep on extending it, till the current cost has overrun the max cost.
Now, when we overrun the max cost, we shrink the window from left, because we have already seen those elements.
At any time, we will keep track of max length of window, because that is the max length of the substring, which we need as output.
#include<string>#include<algorithm>usingnamespace std;
classSolution {
public:int equalSubstring(string s, string t, int maxCost) {
int n = s.size();
int ans =0, currCost =0, left =0;
for (int right =0; right < n; ++right) {
currCost += abs(s[right] - t[right]);
while (currCost > maxCost) {
currCost -= abs(s[left] - t[left]);
++left;
}
ans = max(ans, right - left +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintequalSubstring(String s, String t, int maxCost) {
int n = s.length();
int ans = 0, currCost = 0, left = 0;
for (int right = 0; right < n; right++) {
currCost += Math.abs(s.charAt(right) - t.charAt(right));
while (currCost > maxCost) {
currCost -= Math.abs(s.charAt(left) - t.charAt(left));
left++;
}
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from typing import List
classSolution:
defequalSubstring(self, s: str, t: str, maxCost: int) -> int:
n = len(s)
ans =0 currCost =0 left =0for right in range(n):
currCost += abs(ord(s[right]) - ord(t[right]))
while currCost > maxCost:
currCost -= abs(ord(s[left]) - ord(t[left]))
left +=1 ans = max(ans, right - left +1)
return ans