LeetCode in Kotlin

3090. Maximum Length Substring With Two Occurrences

Easy

Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.

Example 1:

Input: s = “bcbbbcba”

Output: 4

Explanation:

The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba".

Example 2:

Input: s = “aaaa”

Output: 2

Explanation:

The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa".

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun maximumLengthSubstring(s: String): Int {
        val freq = IntArray(26)
        val chars = s.toCharArray()
        var i = 0
        val len = s.length
        var max = 0
        for (j in 0 until len) {
            ++freq[chars[j].code - 'a'.code]
            while (freq[chars[j].code - 'a'.code] == 3) {
                --freq[chars[i].code - 'a'.code]
                i++
            }
            max = max(max, (j - i + 1))
        }
        return max
    }
}