How to find the minimum number of operation(s) to make the string balanced?

后端 未结 5 1654
夕颜
夕颜 2020-12-29 13:27

From Codechef:

A string is considered balanced if and only if all the characters occur in it equal number of times.

You are given a strin

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-29 13:42

    #include 
    #include 
    #include 
    
    int countOps(std::vector &map, int requiredFreq) {
        int countOps = 0, greaterFreq = 0, lesserFreq = 0;
        for (auto a : map) {
            if (a > 0 && a < requiredFreq) {
                lesserFreq =  lesserFreq + abs(requiredFreq - a);
            }
            else if (a > 0 && a > requiredFreq) {
                greaterFreq =  greaterFreq + abs(requiredFreq - a);
            }
        }
        
        countOps = greaterFreq > lesserFreq ? (lesserFreq + (greaterFreq - lesserFreq)) : lesserFreq;
        
        return countOps;
    }
    
    int balanceString(std::string &s, long n){
        
        std::vector map(26, 0);
        int distinctChar = 0;
        int requiredFreq = -1;
        int count = INT_MAX;
        
        // Creating map with frequency and counting distinct chars
        for (char x : s) {
            if (map[x - 'a'] == 0) distinctChar++;
            map[x - 'a']++;
        }
        
        std::sort(std::begin(map), std::end(map), std::greater{});
    
        // If size is multiple of distinctChar
        if (n % distinctChar == 0) {
            requiredFreq = int(n / distinctChar);
            count = countOps(map, requiredFreq);
        }
        else {
            for (int i = 1; i < distinctChar;  i++) {
                if (n % i == 0){
                    requiredFreq = int(n / i);
                    
                    std::vector temp(map.begin(), map.begin() + i);
                    int x = countOps(temp, requiredFreq);
                    count = std::min(count, x);
                }
            }
        }
        
        return count;
    }
    
    int main() {
        std::string s = "aaaaccddefghiii";
        long n = s.size();
        
        if(n <= 1) return 0;
        
        int count = balanceString(s, n);
    
        std::cout << count << std::endl;
        
        return 0;
    }
    

提交回复
热议问题