To solve this problem, we need to determine the minimal cost to make all elements in a sequence the same using two operations: incrementing or decrementing an element by 1, each with a cost of 1.
Approach
The key insight here is that the minimal cost to make all elements equal is achieved by choosing the median of the sequence. This is because the median minimizes the sum of absolute deviations from all elements, which directly translates to the minimal cost in this problem.
Steps to solve the problem:
- Sort the sequence: Sorting helps in easily finding the median.
- Find the median: For a sequence of length (N), the median is at index (N//2) (0-based) after sorting. This works for both even and odd lengths (since any value between the two middle elements in an even-length sequence gives the same minimal cost).
- Calculate the minimal cost: Sum the absolute differences between each element and the median. This sum is the minimal cost.
Solution Code
n = int(input())
arr = list(map(int, input().split()))
arr.sort()
median = arr[n // 2]
total_cost = sum(abs(x - median) for x in arr)
print(total_cost)
Explanation
- Sorting: Sorting the array allows us to quickly locate the median. For example, if the array is [1, 3, 5, 7], sorting gives [1,3,5,7], and the median is at index 2 (element 5).
- Median Selection: The median is chosen because it minimizes the sum of absolute deviations. For even-length arrays, any value between the two middle elements will yield the same minimal cost, so choosing either of them (like the one at index (N//2)) is valid.
- Cost Calculation: The sum of absolute differences between each element and the median gives the total cost, as each difference represents the number of operations needed to make that element equal to the median.
This approach efficiently computes the minimal cost with a time complexity dominated by the sorting step, which is (O(N \log N)), making it suitable for the given problem constraints. The space complexity is (O(1)) (excluding input storage), as we only need to store the sorted array and a few variables.
Answer: The code will output the minimal total cost as required. For example, if the input is 3 elements [1,2,3], the output will be 2. If the input is 4 elements [1,3,5,7], the output will be 8. This confirms the correctness of the approach.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。