简体   繁体   English

非对称交换——通过交换最小化列表中的最大/最小差异

[英]Asymmetric Swaps - minimising max/min difference in list through swaps

Was doing some exercises in CodeChef and came across the Asymmetric Swaps problem:在 CodeChef 中做一些练习并遇到了非对称交换问题:

Problem问题

Chef has two arrays and of the same size. Chef 有两个 arrays 并且大小相同。

In one operation, Chef can:在一次操作中,Chef 可以:

  • Choose two integers and (1 ≤, ≤ ) and swap the elements选择两个整数和 (1 ≤, ≤ ) 并交换元素and. .

Chef came up with a task to find the minimum possible value of ( Chef 想出了一个任务来找到 ( ) after performing the swap operation any (possibly zero) number of times. ) 在执行任意次(可能为零次)交换操作之后。

Since Chef is busy, can you help him solve this task?大厨很忙,你能帮他解决这个任务吗?

Note that注意anddenote the maximum and minimum elements of the array respectively.分别表示数组的最大和最小元素。

I have tried the below logic for the solution.我已经为解决方案尝试了以下逻辑。 But the logic fails for some test cases and I have no access to the failed test cases and where exactly the below code failed to meet the required output.但是某些测试用例的逻辑失败了,我无法访问失败的测试用例,而下面的代码正是无法满足要求的 output。

T = int(input())
for _ in range(T):
    arraySize = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    sortedList = sorted(A+B)
    minLower = sortedList[arraySize-1] - sortedList[0]                # First half of the sortedList
    minUpper = sortedList[(arraySize*2)-1] - sortedList[arraySize]    # Second half of the sortedList
    print(min(minLower,minUpper))

I saw some submitted answers and didn't get the reason or logic why they are doing so.我看到了一些提交的答案,但不明白他们这样做的原因或逻辑。 Can someone guide where am I missing?有人可以指导我在哪里失踪吗?

The approach to sort the input into one list is the right one.将输入排序到一个列表中的方法是正确的。 But it is not enough to look at the left and the right half of that sorted list.但是只看排序列表的左右两边是不够的。

It could well be that there is another sublist of length that has its extreme values closer to each other.很可能存在另一个长度子列表,其极值彼此更接近。

Take for instance this input:以这个输入为例:

A = [1,4,5]
B = [6,11,12]

Then the sorted list is [1,4,5,6,11,12] and [4,5,6] is actually the sublist which minimises the difference between its maximum and minimum value.那么排序列表是 [1,4,5,6,11,12] 和 [4,5,6] 实际上是最小化其最大值和最小值之间的差异的子列表。

So implement a loop where you select the minimum among A[i+N-1] - A[i] .因此,实现一个循环,其中 select 是A[i+N-1] - A[i]中的最小值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM