Get Equal Substrings Within Budget

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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 the ith character of t costs |s[i] - t[i]| (the absolute difference of the ASCII values).

Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a total cost less than or equal to maxCost. If there is no substring that can be changed, return 0.

Examples

Input: s = "abcd", t = "bcdf", maxCost = 3

Output: 3

Explanation: Costs per character: |a-b|=1, |b-c|=1, |c-d|=1, |d-f|=2. The substring "abc" → "bcd" costs 1+1+1=3 ≤ 3, giving length 3.

Input: s = "abcd", t = "cdef", maxCost = 3

Output: 1

Explanation: Costs: 2, 2, 2, 2. Each character costs 2, so at most one character can be changed within budget 3.

Input: s = "abcd", t = "acde", maxCost = 0

Output: 1

Explanation: Costs: 0, 1, 1, 1. Index 0 has cost 0, so a substring of length 1 at index 0 is free.

Constraints

  • 1 <= s.length <= 10^5
  • t.length == s.length
  • 0 <= maxCost <= 10^6
  • s and t consist of lowercase English letters only.
Source: Sliding Window pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle