#K61497. Longest Subsegment with At Most K Distinct Characters
Longest Subsegment with At Most K Distinct Characters
Longest Subsegment with At Most K Distinct Characters
You are given a string s
and an integer K
. Your task is to find the length of the longest contiguous subsegment (substring) of s
that contains at most K
distinct characters.
More formally, if you denote the substring by s[i...j]
(where 0 \le i \le j < n
and n
is the length of s
), you need to maximize j - i + 1
subject to the condition that the number of distinct characters in s[i...j]
is at most K
.
You can represent the condition mathematically as:
$$\text{max length} = \max_{0 \le i \le j < n} \{ j - i + 1 \mid |\{s[i], s[i+1], \ldots, s[j]\}| \le K \} $$If K = 0
or the string is empty, the answer is 0
.
inputFormat
The input is given via standard input (stdin) and consists of two lines:
- The first line contains the string
s
. - The second line contains an integer
K
, which represents the maximum number of distinct characters allowed.
outputFormat
Output a single integer to standard output (stdout) which is the length of the longest contiguous subsegment of s
that contains at most K
distinct characters.
abcba
2
3