Java | Simple and readable | Faster than 97% | Less memory than 100%
A piece of advice\nI definitely recommend you reading this amazing post about using the sliding window pattern for solving Leetcode challanges. Once you underst
## A piece of advice\nI definitely recommend you reading this [amazing post](https://medium.com/leetcode-patterns/leetcode-pattern-2-sliding-windows-for-strings-e19af105316b) about using the sliding window pattern for solving Leetcode challanges. Once you understand the idea, you will see that all the problems look the same and are not actually that hard. Problems that before understanding that post would look impossible for me are now doable.\n\n## Explanation\n- We keep an array (26 positions as the problem states that the input only contains lowercase english letters) that counts the ocurrences of each letter inside the current window.\n- We keep a variable with the amount of distincts letter inside the window.\n- In every iteration we increase the window but in an inner loop we add all **valid** combinations while shrinking the window.\n\n## Code\n```\nclass Solution {\n    public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {\n        Map<String, Integer> occurrences = new HashMap<>();\n        // Count ocurrences per letter inside window\n        int[] countLetters = new int[26];\n        // Count total amount of unique letters inside window\n        int countUnique = 0;\n        int left = 0;\n        int right = 0;\n        \n        while (right < s.length()){\n            // Add new character to the window\n            char r = s.charAt(right++);\n            countLetters[r - \'a\']++;\n            \n            // If it\'s the first time we see this character increase unique\n            if (countLetters[r - \'a\'] == 1) {\n                countUnique++;\n            }\n\n            while ((right - left) >= minSize && (right - left) <= maxSize) {\n                if (countUnique <= maxLetters) {\n                    String subs = s.substring(left, right);\n                    occurrences.put(subs, occurrences.getOrDefault(subs, 0) + 1);\n                }\n                \n                char l = s.charAt(left++);\n                countLetters[l - \'a\']--;\n                \n                // Unique character left the window\n                if (countLetters[l - \'a\'] == 0) {\n                    countUnique--;\n                }\n            }\n        }\n        \n        return occurrences.entrySet().stream().map(Map.Entry::getValue).max(Comparator.naturalOrder()).orElse(0);\n    }\n}\n```\n\nHope you liked the post, and now some shameless self-promotion: My blog where I also post explanations to LeetCode challenges https://pablomusumeci.com/categories/#leetcode
['Sliding Window', 'Java']