LeetCode in Kotlin

3960. Frequency Balance Subarray

Medium

You are given an integer array nums.

Define a frequency balance non-empty subarrays as follows:

Return an integer denoting the length of the longest frequency balance subarray.

Example 1:

Input: nums = [1,2,2,1,2,3,3,3]

Output: 5

Explanation:

Example 2:

Input: nums = [5,5,5,5]

Output: 4

Explanation:

Example 3:

Input: nums = [1,2,3,4]

Output: 1

Explanation:

Since all elements appear only once, the length of the longest frequency balance subarray is 1.

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun getLength(a: IntArray): Int {
        val n = a.size
        var ans = 1
        for (i in 0..<n) {
            val mp: MutableMap<Int?, Int?> = HashMap<Int?, Int?>()
            val fq = IntArray(n + 1)
            var mx = 0
            var s = 0
            for (j in i..<n) {
                val old: Int = mp.getOrDefault(a[j], 0)!!
                if (old > 0) {
                    fq[old]--
                }
                mp.put(a[j], old + 1)
                fq[old + 1]++
                if (old + 1 > mx) {
                    mx = old + 1
                    s = 1
                } else if (old + 1 == mx) {
                    s++
                }
                val distinct = mp.size
                if (distinct == 1 || (mx % 2 == 0 && s < distinct && fq[mx / 2] == distinct - s)) {
                    ans = max(ans, j - i + 1)
                }
            }
        }
        return ans
    }
}