Easy
You are given an integer array nums and an integer k.
Find the absolute difference between:
k largest elements in the array; andk smallest elements in the array.Return an integer denoting this difference.
Example 1:
Input: nums = [5,2,2,4], k = 2
Output: 5
Explanation:
k = 2 largest elements are 4 and 5. Their sum is 4 + 5 = 9.k = 2 smallest elements are 2 and 2. Their sum is 2 + 2 = 4.abs(9 - 4) = 5.Example 2:
Input: nums = [100], k = 1
Output: 0
Explanation:
abs(100 - 100) = 0.Constraints:
1 <= n == nums.length <= 1001 <= nums[i] <= 1001 <= k <= nimport 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;
}
}