To solve this problem, we need to determine the minimum number of operations required to make all elements in a list equal. The allowed operations are incrementing or decrementing an element by 1.
Approach
The key insight here is that the median of the list minimizes the sum of absolute differences between each element and the target value. This is because the median is the middle value of the sorted list, and it balances the number of elements on either side, leading to the smallest total number of operations.
Steps to solve the problem:
- Sort the list: This helps in easily finding the median.
- Find the median: For a sorted list, the median is at index
len(list) // 2(works for both even and odd lengths, as the sum of absolute differences remains the same for any value between the two middle elements in even-length lists). - Calculate the total operations: Sum the absolute differences between each element and the median. This sum gives the minimal number of operations needed.
Solution Code
def min_operations(nums):
nums_sorted = sorted(nums)
median = nums_sorted[len(nums_sorted) // 2]
return sum(abs(x - median) for x in nums_sorted)
Explanation
Let’s break down the solution with examples:
-
Example 1: List
[1, 2, 3]
Sorted list:[1,2,3], median is2.
Total operations:|1-2| + |2-2| + |3-2| = 1+0+1 = 2. -
Example 2: List
[1,10,2,9]
Sorted list:[1,2,9,10], median is9(index4//2=2).
Total operations:|1-9| + |2-9| + |9-9| + |10-9| =8+7+0+1=16. -
Example3: List
[4,1,5,2,3]
Sorted list:[1,2,3,4,5], median is3.
Total operations:|1-3| + |2-3| + |3-3| + |4-3| + |5-3| =2+1+0+1+2=6.
This approach efficiently computes the minimal operations with a time complexity dominated by the sorting step: O(n log n) (where n is the length of the list). The space complexity is O(n) for the sorted list (or O(1) if we sort in place, but in Python, sorted() creates a new list).
This solution is optimal and handles all edge cases (like single-element lists, even/odd lengths) correctly. It’s a classic problem that leverages the properties of the median to find the minimal sum of absolute differences.


作者声明:本文包含人工智能生成内容。