LeetCode in Kotlin

2256. Minimum Average Difference

Medium

You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Note:

Example 1:

Input: nums = [2,5,3,9,5,3]

Output: 3

Explanation:

The average difference of index 3 is the minimum average difference so return 3.

Example 2:

Input: nums = [0]

Output: 0

Explanation:

The only index is 0 so return 0.

The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.

Constraints:

Solution

class Solution {
    fun minimumAverageDifference(nums: IntArray): Int {
        var numsSum: Long = 0
        for (num in nums) {
            numsSum += num.toLong()
        }
        var minAverageDiff = Long.MAX_VALUE
        var sumFromFront: Long = 0
        var index = 0
        for (i in nums.indices) {
            sumFromFront += nums[i].toLong()
            val numbersRight = if (i == nums.size - 1) 1 else nums.size - i - 1
            val averageDiff = Math.abs(sumFromFront / (i + 1) - (numsSum - sumFromFront) / numbersRight)
            if (minAverageDiff > averageDiff) {
                minAverageDiff = averageDiff
                index = i
            }
            if (averageDiff == 0L) {
                break
            }
        }
        return index
    }
}