We don't need to compare the max length every time during the iteration. Since the maximum length substring will only extend its length when its start is increased, the final maximum length will be the end position (the length of s) minus the start variable. This is also the same idea from LC Longest Repeating Character Replacement

public int lengthOfLongestSubstringKDistinct(String s, int k) { int[] count = new int[128]; int max=0; int start=0; for(int i=0;i<s.length();i++) { if(count[(int) s.charAt(i)]++==0) max++; if(max>k) { if(--count[(int) s.charAt(start)]==0) max--; start++; } } return s.length()-start; }Longest Substring with At Most K Distinct Characters