题目:
有两个序列a,b, 大小都为n, 序列元素的值为任意整形数,无序:
要求: 通过交换a,b中的元素,是[序列a元素的和]与[序列b元素的和]之间的差最小。
(从我之前的一个博客搬迁过来,没什么问题吧?)
我李泽军Thomas的解答:
# this solution is based on greedy algorithm ,its result is not optimal.
# comparing the solution on the web, this solution have better results for some test suit, but
# worse results for some , and the same for others
# def min_custom(a,b,n):
def min_custom(new):
# new = a + b
# print new
# greedy algorithm first
a = []
b = []
# print sb
length = len(new)/2
for i in xrange(length):
sa = sum(a)
sb = sum(b)
pop_a = new.pop()
pop_b = new.pop()
bigger = max(pop_a,pop_b)
smaller = min(pop_a,pop_b)
if(sa > sb):
a.append(smaller)
b.append(bigger)
else:
a.append(bigger)
b.append(smaller)
print a,b
difference = sum(a) - sum(b)
print difference
# a = [3,4,5]
# b= [6,7,4]
# min_custom(a,b,len(a))
# a = [3,4,5]
# b= [6,7,4]
# min_custom(a,b,len(a))
ne = [1, 2, 3, 4, 5, 6, 700, 800] # my 97, better than 99
min_custom(ne)
ne = [1, 50, 90, 100, 10000, 10001] # my 38, worth than 40
min_custom(ne)
ne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 1, the same
min_custom(ne)
ne = [1, 1, 2, 3, 29, 30, 210, 232, 12311, 12312] # abs(-19)= 19 , better than 21
min_custom(ne)