#K94542. Longest Substring with At Most K Distinct Characters
Longest Substring with At Most K Distinct Characters
Longest Substring with At Most K Distinct Characters
You are given an integer k
and a string s
. Your task is to find the length of the longest substring of s
that contains at most k
distinct characters. In other words, find the maximum length l such that there exists a substring of s
with length l and its number of unique characters does not exceed k
.
You can use the sliding window technique to solve the problem efficiently. Formally, if we denote the substring by s[i..j]
(inclusive of i
and exclusive of j
), you need to satisfy:
and maximize \(j-i\). Good luck!
inputFormat
The input consists of two lines:
- The first line contains an integer
k
. - The second line contains the string
s
.
You can assume that s
contains only printable characters and its length is at most 106.
outputFormat
Output a single integer, which is the length of the longest substring that contains at most k
distinct characters.
2
eceba
3