#3774

Absolute Difference Between Maximum and Minimum K Elements

Easy
ArraySortingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Sort the array in ascending order.
  2. 2Step 2: Sum the first k elements for the smallest sum.
  3. 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.