[Leetcode] 3442. Maximum Difference Between Even and Odd Frequency I

whitehousechef·2025년 6월 10일

https://leetcode.com/problems/maximum-difference-between-even-and-odd-frequency-i/description/?envType=daily-question&envId=2025-06-10

initial

a v simple q but I did a sort on my dictionary to get lowest and highest value

from collections import Counter
class Solution:
    def maxDifference(self, s: str) -> int:
        dic = Counter(s)
        dic = dict(sorted(dic.items()))
        minVal=int(10e18)
        maxVal=0
        for key,value in dic.items():
            if value%2==1:
                maxVal=max(maxVal,value)
            else:
                minVal=min(minVal,value)
        return maxVal-minVal

sol

actually if we dont use a dictionary and use a array of size 26 and store the frequencies of each character in there, we dont have to sort.

Cuz we can iterate through that array and get the min and max value with 2 external variables

class Solution:
    def maxDifference(self, s):
        mpp = [0] * 26
        maxi = 0
        mini = len(s)
        for c in s:
            mpp[ord(c) - ord('a')] += 1
        for i in range(26):
            if mpp[i] % 2 != 0:
                maxi = max(maxi, mpp[i])
            if mpp[i] % 2 == 0 and mpp[i] > 0:
                mini = min(mini, mpp[i])
        return maxi - mini

complexity

my intiial sol is n log n cuz of sort but this one is n time
1 space

0개의 댓글