LeetCode in Kotlin

2607. Make K-Subarray Sums Equal

Medium

You are given a 0-indexed integer array arr and an integer k. The array arr is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.

You can do the following operation any number of times:

Return the minimum number of operations such that the sum of each subarray of length k is equal.

A subarray is a contiguous part of the array.

Example 1:

Input: arr = [1,4,1,3], k = 2

Output: 1

Explanation: we can do one operation on index 1 to make its value equal to 3. The array after the operation is [1,3,1,3]

Example 2:

Input: arr = [2,5,5,7], k = 3

Output: 5

Explanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5. The array after the operations is [5,5,5,5]

Constraints:

Solution

import java.util.ArrayList

internal class Solution {
    fun makeSubKSumEqual(arr: IntArray, k: Int): Long {
        val n = arr.size
        var ans: Long = 0
        val vis = IntArray(n)
        var i = 0
        while (i < n) {
            val list: MutableList<Int> = ArrayList()
            if (vis[i] == 1) {
                i++
                continue
            }
            while (vis[i] == 0) {
                vis[i] = 1
                list.add(arr[i])
                i = (i + k) % n
            }
            list.sort()
            for (j in list) {
                ans += kotlin.math.abs(j - list[list.size / 2]).toLong()
            }
            i++
        }
        return ans
    }
}