LeetCode in Kotlin

2808. Minimum Seconds to Equalize a Circular Array

Medium

You are given a 0-indexed array nums containing n integers.

At each second, you perform the following operation on the array:

Note that all the elements get replaced simultaneously.

Return the minimum number of seconds needed to make all elements in the array nums equal.

Example 1:

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

Output: 1

Explanation: We can equalize the array in 1 second in the following way:

Example 2:

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

Output: 2

Explanation: We can equalize the array in 2 seconds in the following way:

It can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.

Example 3:

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

Output: 0

Explanation: We don’t need to perform any operations as all elements in the initial array are the same.

Constraints:

Solution

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

class Solution {
    fun minimumSeconds(nums: List<Int>): Int {
        val n = nums.size
        var min = n / 2
        val hm = HashMap<Int, MutableList<Int>>()
        for (i in 0 until n) {
            val v = nums[i]
            hm.computeIfAbsent(v) { _: Int? -> ArrayList() }.add(i)
        }
        for (list in hm.values) {
            if (list.size > 1) {
                var curr = (list[0] + n - list[list.size - 1]) / 2
                for (i in 1 until list.size) {
                    curr = max(curr.toDouble(), ((list[i] - list[i - 1]) / 2).toDouble()).toInt()
                }
                min = min(min.toDouble(), curr.toDouble()).toInt()
            }
        }
        return min
    }
}