https://leetcode.com/problems/substring-with-largest-variance/

 

Substring With Largest Variance - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

같은 알고리즘인데 파이썬은 안되고 c++은 되네.. 역시 파이썬은 느리다 ㅠ

class Solution {
public:
    int largestVariance(string s) {
        int count[150] = {0,};
        int answer = 0;
        for(int i = 0; i < s.length(); i++){
            count[s[i]]++;
        }
        for(char c1 = 'a'; c1 <= 'z'; c1++){
            for(char c2 = 'a'; c2 <= 'z'; c2++){
                if (c1 == c2 || !count[c1] || !count[c2]) continue;
                
                int f1 = 0, f2 = 0;
                for(int i = 0; i < s.length(); i++){
                    if (s[i] == c1) f1++;
                    if (s[i] == c2) f2++;
                    if (f1 < f2) f1 = f2 = 0;
                    if (f1 && f2) answer = max(answer, f1 - f2);
                }
                
                f1 = f2 = 0;
                for(int i = s.length() - 1; i >= 0; i--){
                    if (s[i] == c1) f1++;
                    if (s[i] == c2) f2++;
                    if (f1 < f2) f1 = f2 = 0;
                    if (f1 && f2) answer = max(answer, f1 - f2);
                }
            }
        }
        
        return answer;
    }
};

 

+ Recent posts