Get Equal Substrings Within Budget

Medium Topics Company Tags

The lowercase strings s and t have equal length. Changing s[i] to t[i] costs the absolute difference between their character codes; for example, changing a to d costs 3. Choose one contiguous interval and change its characters in s to match the characters at the same positions in t. Return the greatest interval length whose total cost is at most maxCost. Return 0 if no nonempty interval fits the budget.

Example 1:

Input: s = "abc"
t = "bcd"
maxCost = 2

Output: 2

Explanation: Each position costs 1 to change. Any two consecutive positions cost 2 and fit the budget, but all three cost 3. The maximum length is 2.

Example 2:

Input: s = "aaz"
t = "abz"
maxCost = 0

Output: 1

Explanation: The middle position costs 1, while the first and last positions already match. With a zero budget, either matching position can be chosen alone. They are not consecutive, so the maximum length is 1.

Example 3:

Input: s = "az"
t = "za"
maxCost = 24

Output: 0

Explanation: Each position costs 25 to change between a and z. The budget is only 24, so no nonempty interval is affordable and the answer is 0.

Constraints:

  • 1 <= s.length <= 100000
  • t.length == s.length
  • s and t contain only lowercase English letters.
  • 0 <= maxCost <= 1000000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.