All problems
0718MediumStringBinary SearchSliding WindowPrefix Sum

Longest Stretch Retinted Within Budget

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1208Get Equal Substrings Within Budget

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A ribbon press holds two rolls of the same length. Every position on a roll carries one shade, written as a lowercase letter, so panel and pattern are strings of equal length and panel[i], pattern[i] are the shades sitting at position i on the two rolls.

Give each letter its place in the alphabet, with "a" worth 0 and "z" worth 25. Retinting one position of panel so that it carries the shade pattern has at that position costs the absolute difference of the two values in units of ink, so a position that already carries the right shade costs nothing.

You hold budget units of ink. Pick one contiguous stretch of positions and retint every position inside it so the stretch matches pattern there, spending at most budget units in total across the stretch. Positions outside the stretch are left alone.

Return the number of positions in the longest stretch you can finish. An empty stretch is always allowed and has length 0.

Examples

Example 1

Input
panel = "dqgh", pattern = "cqfi", budget = 2
Output
3

Retinting positions 0, 1 and 2 costs 1 + 0 + 1 = 2 units of ink, which the budget covers, and that stretch holds 3 positions.

Example 2

Input
panel = "wq", pattern = "aa", budget = 0
Output
0

Position 0 needs 22 units and position 1 needs 16, so with no ink at all only the empty stretch is affordable.

Example 3

Input
panel = "cbbb", pattern = "aaaa", budget = 3
Output
3

The four positions need 2, 1, 1 and 1 units. Positions 1, 2 and 3 together need 3 units, which the budget covers, and that stretch holds 3 positions.

Constraints

  • 1 <= panel.length <= 10^5
  • pattern.length == panel.length
  • 0 <= budget <= 10^6
  • panel and pattern hold lowercase English letters only.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def longest_retinted_stretch(panel: str, pattern: str, budget: int) -> int:
Java
public int longestRetintedStretch(String panel, String pattern, int budget)
September 7
Apply