#3774
Easy Algorithms Absolute difference between maximum and minimum k elements
Array Sorting
75.4% acceptance
Feb 25, 2026
38
2
You are given an integer array nums and an integer k.
Find the absolute difference between:
the sum of the k largest elements in the array; and
the sum of the k smallest elements in the array.
Return an integer denoting this difference.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn abs_difference(nums: Vec<i32>, k: i32) -> i32 {
let mut s = nums.clone();
s.sort();
let n = s.len();
let k = k as usize;
let sum_max: i64 = s[n - k..].iter().map(|&x| x as i64).sum();
let sum_min: i64 = s[..k].iter().map(|&x| x as i64).sum();
(sum_max - sum_min).abs() as i32
}
}