#K2596. Longest Balanced Substring
Longest Balanced Substring
Longest Balanced Substring
You are given a string s
consisting solely of the characters 'x'
and 'y'
. A substring of s
is considered balanced if it contains an equal number of 'x'
and 'y'
. Your task is to determine the length of the longest balanced substring within s
.
More formally, let S be a string of length n such that S[i] \in \{'x', 'y'\} for all 0 \le i < n. Find the maximum length L such that there exists indices i and j (with i < j) for which the substring S[i...j] is balanced, i.e., \[ \#\{ k | S[k] = 'x',\, i \leq k \leq j \} = \#\{ k | S[k] = 'y',\, i \leq k \leq j \}. \] If no such substring exists, output 0.
Example:
- Input:
xyxyxxxyy
→ Output:8
- Input:
xxyyy
→ Output:4
- Input:
xxx
→ Output:0
inputFormat
The input consists of a single line containing a non-empty string s
comprised only of the characters 'x'
and 'y'
.
outputFormat
Output a single integer representing the length of the longest balanced substring found in s
. If no balanced substring exists, output 0.
xyxyxxxyy
8