LeetCode-in-Java

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

import java.util.Arrays;

public class Solution {
    public int absDifference(int[] nums, int k) {
        Arrays.sort(nums);
        int maxSum = 0;
        int minSum = 0;
        for (int i = 0, j = nums.length - 1; i < k; i++, j--) {
            minSum += nums[i];
            maxSum += nums[j];
        }
        return maxSum - minSum;
    }
}