#K94542. Longest Substring with At Most K Distinct Characters

    ID: 38664 Type: Default 1000ms 256MiB

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:

{s[x]:ix<j}k|\{ s[x] : i \le x < j \}| \le k

and maximize \(j-i\). Good luck!

inputFormat

The input consists of two lines:

  1. The first line contains an integer k.
  2. 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.

## sample
2
eceba
3