LeetCode 2272: Substring With Largest Variance

Problem Description

Explanation

To solve this problem, we can iterate through all substrings of the given string s and calculate the variance for each substring. For each substring, we count the occurrences of each character and find the difference between the maximum and minimum occurrence. We track the maximum variance seen so far and return it at the end.

  • We use two pointers to define the substring window.
  • We maintain a hashmap to keep track of the count of characters within the window.
  • We slide the window to cover all possible substrings and calculate the variance for each.

Time Complexity: O(N^2) where N is the length of the input string s. Space Complexity: O(26) - since we are using a hashmap to store the count of characters.

Solutions

class Solution {
    public int largestVariance(String s) {
        int maxVariance = 0;
        for (int i = 0; i < s.length(); i++) {
            int[] count = new int[26];
            for (int j = i; j < s.length(); j++) {
                count[s.charAt(j) - 'a']++;
                int maxCount = 0, minCount = Integer.MAX_VALUE;
                for (int c : count) {
                    if (c > 0) {
                        maxCount = Math.max(maxCount, c);
                        minCount = Math.min(minCount, c);
                    }
                }
                maxVariance = Math.max(maxVariance, maxCount - minCount);
            }
        }
        return maxVariance;
    }
}

Loading editor...