LeetCode in Kotlin

3774. Absolute Difference Between Maximum and Minimum K Elements

Easy

You are given an integer array nums and an integer k.

Find the absolute difference between:

Return an integer denoting this difference.

Example 1:

Input: nums = [5,2,2,4], k = 2

Output: 5

Explanation:

Example 2:

Input: nums = [100], k = 1

Output: 0

Explanation:

Constraints:

Solution

class Solution {
    fun absDifference(nums: IntArray, k: Int): Int {
        nums.sort()
        var maxSum = 0
        var minSum = 0
        var i = 0
        var j = nums.size - 1
        while (i < k) {
            minSum += nums[i]
            maxSum += nums[j]
            i++
            j--
        }
        return maxSum - minSum
    }
}