
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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int equalSubstring(char * s, char * t, int maxCost) {
6 int n = strlen(s);
7 int start = 0, end = 0, cost = 0, maxLength = 0;
8
9 while (end < n) {
10 int diff = abs(s[end] - t[end]);
11 cost += diff;
12 while (cost > maxCost) {
13 cost -= abs(s[start] - t[start]);
14 start++;
15 }
16 maxLength = fmax(maxLength, end - start + 1);
17 end++;
18 }
19
20 return maxLength;
21}
22
23int main() {
24 char s[] = "abcd";
25 char t[] = "bcdf";
26 int maxCost = 3;
27 printf("%d\n", equalSubstring(s, t, maxCost));
28 return 0;
29}The implementation starts by initializing pointers for the start, end of the current window, and an integer for tracking the current cost. We iterate through each character, calculating the cost of changing one character to the other. If the accumulated cost exceeds maxCost, we shrink the window from the left by incrementing the start pointer and updating the cost accordingly. We track the maximum window length for which the cost is within the allowed limit. Finally, the function returns this maximum length.
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 Python solution uses the bisect module for binary search to maintain a sorted order within the prefix sum array. The search returns the proper position for the farthest valid index which doesn't exceed the max allowable cost, increasing algorithm efficiency considerably.