
Sponsored
Sponsored
This approach uses the sliding window technique to efficiently determine the maximum substring length that can be changed within the given cost. We maintain a window of characters from the strings s and t and slide it over the strings. We continuously calculate the cost for converting the current window substring from s to t. Whenever the cost exceeds maxCost, we shrink the window from the left to keep the cost under control. The maximum width of this window during traversal is the answer.
Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(1), as the solution uses only a fixed amount of extra space.
1function equalSubstring(s, t, maxCost) {
2 let start = 0, cost = 0, maxLength = 0;
3
4 for (let end = 0; end < s.length; end++) {
5 cost += Math.abs(s.charCodeAt(end) - t.charCodeAt(end));
6
7 while (cost > maxCost) {
8 cost -= Math.abs(s.charCodeAt(start) - t.charCodeAt(start));
9 start++;
10 }
11 maxLength = Math.max(maxLength, end - start + 1);
12 }
13
14 return maxLength;
15}
16
17console.log(equalSubstring("abcd", "bcdf", 3));This JavaScript function utilizes a sliding window over the characters of the input strings. It calculates a running cost of the conversions and adjusts the window by moving the start index when the cost becomes too high. This way, it finds and returns the maximum possible length of the substring that can be changed within the allowable cost.
This approach makes use of the prefix sum array to store accumulated costs and binary search to find the furthest valid endpoint for every starting point. First, calculate the prefix sum that stores the total cost from the beginning to any character index. Then, for each start point, use binary search to find the furthest valid end point where the total transformation cost still doesn't exceed maxCost.
Time Complexity: O(n log n), where n is the length of the string s due to the binary search iterations for each starting point.
Space Complexity: O(n), as it requires space for the prefix sum array.
This Java version also creates a prefix sum array and employs binary search to quickly find the furthest valid substring end for each start index, keeping the prefix sum within the budget. Adjustments to Java's native binary search are made to handle possible negative indices for non-exact matches.