LeetCode in Kotlin

3442. Maximum Difference Between Even and Odd Frequency I

Easy

You are given a string s consisting of lowercase English letters. Your task is to find the maximum difference between the frequency of two characters in the string such that:

Return the maximum difference, calculated as the frequency of the character with an odd frequency minus the frequency of the character with an even frequency.

Example 1:

Input: s = “aaaaabbc”

Output: 3

Explanation:

Example 2:

Input: s = “abcabcab”

Output: 1

Explanation:

Constraints:

Solution

import kotlin.math.max
import kotlin.math.min

class Solution {
    fun maxDifference(s: String): Int {
        val freq = IntArray(26)
        var maxOdd = 0
        var minEven = 1000
        for (i in 0..<s.length) {
            freq[s[i].code - 'a'.code]++
        }
        for (j in freq) {
            if (j != 0 && j % 2 == 0) {
                minEven = min(minEven, j)
            } else {
                maxOdd = max(maxOdd, j)
            }
        }
        return maxOdd - minEven
    }
}