Given a string s and an integer k, return the maximum length of a contiguous substring of s that contains at most k distinct characters.
Constraints:
Input: s = "eceba"-str, k = 2-int
Output: 3-int
Explanation: The longest substring with at most 2 distinct characters is "ece" (distinct characters: {e, c}), which has length 3.
Input: s = "aa"-str, k = 1-int
Output: 2-int
Explanation: The entire string "aa" contains only 1 distinct character, so the maximum length is 2.
Input: s = "araaci"-str, k = 2-int
Output: 4-int
Explanation: The longest valid substring is "araa" (distinct characters: {a, r}), with length 4.
Input: s = "araaci"-str, k = 1-int
Output: 2-int
Explanation: With only 1 distinct character allowed, the best you can do is "aa", so the maximum length is 2.
Input: s = "cbbebi"-str, k = 3-int
Output: 5-int
Explanation: The longest substring with at most 3 distinct characters is "cbbeb" (distinct characters: {c, b, e}), with length 5.
Input: s = "abc"-str, k = 0-int
Output: 0-int
Explanation: This is an edge case with k = 0: no non-empty substring can have at most 0 distinct characters, so the answer is 0.
Now, let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem: