
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.
1using System;
2
3public class Solution {
4 public int EqualSubstring(string s, string t, int maxCost) {
5 int start = 0, cost = 0, maxLength = 0;
6
7 for (int end = 0; end < s.Length; ++end) {
8 cost += Math.Abs(s[end] - t[end]);
9 while (cost > maxCost) {
10 cost -= Math.Abs(s[start] - t[start]);
11 start++;
12 }
13 maxLength = Math.Max(maxLength, end - start + 1);
14 }
15
16 return maxLength;
17 }
18
19 public static void Main(string[] args) {
20 Solution sol = new Solution();
21 Console.WriteLine(sol.EqualSubstring("abcd", "bcdf", 3));
22 }
23}This C# solution makes use of the sliding window technique. The program tracks the running cost of converting substring s to t. If the window's cost exceeds maxCost, it is adjusted by moving the start index, and the cost is updated. The solution returns the largest valid substring length found.
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 JavaScript implementation constructs a cumulative prefix sum array, manually iterating through potential substring end points by comparison, effectively achieving binary search capabilities, hence optimizing examining process for converting strings within budgeted cost.