Get Equal Substrings Within Budget

You are given two strings `s` and `t` of the same length and an integer `maxCost`. Changing `s[i]` into `t[i]` costs `|s[i] - t[i]|` (the difference of their ASCII codes). Return the maximum length of a substring of `s` that can be changed into the matching substring of `t` with total cost at most `maxCost`, or `0` if none can.

30:00

Get Equal Substrings Within Budget
medium
Free written solution
Topics
Companies

You are given two strings s and t of the same length and an integer maxCost. Changing s[i] into t[i] costs |s[i] - t[i]| (the difference of their ASCII codes). Return the maximum length of a substring of s that can be changed into the matching substring of t with total cost at most maxCost, or 0 if none can.

Example 1:
Input: {"s":"abcd","t":"bcdf","maxCost":3}
Output: 3
Constraints:
  • 1≤s.length≤1051 \leq \text{s.length} \leq 10^5

  • t.length=s.length\text{t.length} = \text{s.length}

  • 0≤maxCost≤1060 \leq \text{maxCost} \leq 10^6

  • s and t consist of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"abcd","t":"bcdf","maxCost":3}

Each column i costs |s[i] - t[i]|. Find the widest run of columns whose costs add up to at most 3.

s over t, bridge height = change cost

a

b

1

b

c

1

c

d

1

d

f

2

.

.

.

.

budget spent by the window

0 / 3

| maxCost 3

window = empty

best = 0

Variables
VariableValue
maxCost3
left0
cost0
best0
DepthFunction Call
Stack empty
0/10