#3774
Absolute Difference Between Maximum and Minimum K Elements
EasyArraySortingSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
Sorting the array allows us to easily access the k largest and k smallest elements directly, making the solution efficient.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array in ascending order.
- 2Step 2: Sum the first k elements for the smallest sum.
- 3Step 3: Sum the last k elements for the largest sum and return their absolute difference.
solution.py3 lines
1def max_min_difference(nums, k):
2 nums.sort()
3 return abs(sum(nums[-k:]) - sum(nums[:k]))ℹ
Complexity note: Sorting the array dominates the time complexity, making it O(n log n).
- 1Sorting simplifies finding k largest and smallest elements.
- 2Absolute difference can be computed directly from sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.