Absolute Difference Between Maximum and Minimum K Elements Problem
#3774
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3774.
You are given an integer array nums and an integer k.
Find the absolute difference between:
- the sum of the
klargest elements in the array; and - the sum of the
ksmallest elements in the array.
Return an integer denoting this difference.
Example 1:
Input: nums = [5,2,2,4], k = 2
Output: 5
Explanation:
- The k = 2 largest elements are 4 and 5. Their sum is 4 + 5 = 9.
- The k = 2 smallest elements are 2 and 2. Their sum is 2 + 2 = 4.
- The absolute difference is abs(9 - 4) = 5.
Example 2:
Input: nums = [100], k = 1
Output: 0
Explanation:
- The largest element is 100.
- The smallest element is 100.
- The absolute difference is abs(100 - 100) = 0.
Constraints:
1 <= n == nums.length <= 1001 <= nums[i] <= 1001 <= k <= n
Solution
Approach: Sorting
Sort nums. The sum of the k largest elements is the sum of the last k entries and the sum of the k smallest is the sum of the first k entries. Return their difference.
Complexity: time O(n log n), space O(log n), where n is the length of nums.
class Solution:
def absDifference(self, nums: List[int], k: int) -> int:
nums.sort()
return sum(nums[-k:]) - sum(nums[:k])